板球比赛得分统计功能实现咨询:是否应采用数组作为数据结构?
Great question—arrays (or lists, depending on your programming language) are absolutely a solid choice for implementing this cricket scoring system, and they’ll make tracking batsmen scores and dynamic game state much easier. Let me break down why they work so well, plus walk through a clear implementation logic tailored to your requirements.
Why Arrays/Lists Are Ideal
- They let you track batsmen scores in order: Each index in the array corresponds to a batsman (1st at index 0, 2nd at 1, etc.), making it trivial to update or retrieve individual scores.
- They support dynamic changes: When a wicket falls, you can easily remove the out batsman’s score from the array and add a new entry for the incoming batsman (starting at 0 runs).
- They simplify calculations: You can quickly sum all elements to cross-verify total runs (total runs = sum(batsmen_scores) + extras) or loop through to format the final batsmen score output.
Step-by-Step Implementation Logic
Let’s map this to your sample input and rules, using a list (array) for batsmen scores as the core structure:
1. Initialize Core Variables
First, set up all the stats you need to track:
total_runs: Starts at 0wickets: Starts at 0extras: Starts at 0batsmen_scores: A list initialized with[0, 0](since two batsmen start the game)current_batsman: Index of the batsman currently striking (start at 0 for the 1st batsman)balls_bowled: Counts valid deliveries (to calculate overs later)
2. Process Each Entry in the Input
Loop through every score entry from the input, handling each case based on the rules:
- Normal runs (e.g., "1", "3"):
- Add runs to
total_runsand the current batsman’s score inbatsmen_scores - Increment
balls_bowledby 1 - If runs are odd, swap
current_batsman(since odd runs mean the batsmen switch ends)
- Add runs to
- Wide ball ("1wd"):
- Add 1 to
total_runsandextras - Do NOT increment
balls_bowled(wide balls are re-bowled)
- Add 1 to
- No-ball ("2nb"):
- Add 1 to
total_runsandextras(for the no-ball penalty) - Add the numeric part (2, in this case) to
total_runsand the current batsman’s score - Do NOT increment
balls_bowled(no-balls are re-bowled) - If the numeric part is odd, swap
current_batsman
- Add 1 to
- Wicket ("0wkt"):
- Increment
wicketsby 1 - Increment
balls_bowledby 1 - Remove the out batsman’s score from
batsmen_scores(using their current index) - Append
0tobatsmen_scoresfor the new incoming batsman - Swap
current_batsmanto the non-out batsman (since the out batsman was striking)
- Increment
- Leg bye ("lb"):
- Add the numeric part to
total_runsandextras - Increment
balls_bowledby 1 - If runs are odd, swap
current_batsman
- Add the numeric part to
3. Calculate Overs
Overs are calculated as total_balls // 6 + (total_balls % 6)/10 (e.g., 8 balls = 1.2 overs).
4. Format the Final Output
Loop through batsmen_scores to generate the string for each batsman’s score, then combine all stats into the final output matching your sample.
Example Pseudocode (Python)
Here’s how this logic translates to code, using a list (Python’s version of an array) for batsmen_scores:
# Initialize game state total_runs = 0 wickets = 0 extras = 0 batsmen_scores = [0, 0] current_batsman = 0 balls_bowled = 0 # Split sample input into individual entries input_entries = "1 0 1wd 0 3 2 0 0 2nb 0wkt 6 1 0 4".split() for entry in input_entries: if "wd" in entry: # Handle wide ball total_runs += 1 extras += 1 elif "nb" in entry: # Handle no-ball: extract runs first runs = int(entry.replace("nb", "")) total_runs += 1 + runs extras += 1 batsmen_scores[current_batsman] += runs # Swap batsman if runs are odd if runs % 2 != 0: current_batsman = 1 - current_batsman elif "wkt" in entry: # Handle wicket wickets += 1 balls_bowled += 1 # Remove out batsman, add new one batsmen_scores.pop(current_batsman) batsmen_scores.append(0) # Switch to the non-striking batsman current_batsman = 1 - current_batsman if len(batsmen_scores) == 2 else 0 elif "lb" in entry: # Handle leg bye runs = int(entry.replace("lb", "")) total_runs += runs extras += runs balls_bowled += 1 if runs % 2 != 0: current_batsman = 1 - current_batsman else: # Normal runs runs = int(entry) total_runs += runs batsmen_scores[current_batsman] += runs balls_bowled += 1 if runs % 2 != 0: current_batsman = 1 - current_batsman # Calculate overs overs = f"{balls_bowled // 6}.{balls_bowled % 6}" if balls_bowled % 6 != 0 else f"{balls_bowled//6}" # Format batsmen scores output scores_str = [] for idx, score in enumerate(batsmen_scores): if idx == 0: scores_str.append(f"1st batsmen: {score} runs") elif idx == 1: scores_str.append(f"2nd batsmen: {score} runs") else: scores_str.append(f"{idx+1}rd batsmen: {score} runs") scores_output = "; ".join(scores_str) # Print final result print(f"total runs scored: {total_runs}, number of wickets: {wickets}, extras: {extras}, scores by batsmen: {scores_output}, number of overs bowled: {overs}")
When you run this with your sample input, it’ll output exactly what you expect (adjusting for any minor rule edge cases, like strike after a wicket).
Key Takeaway
Arrays/lists are perfect here because they let you dynamically manage the changing set of batsmen while keeping their scores organized and easy to access. This structure will scale well even if more wickets fall and more batsmen come in.
内容的提问来源于stack exchange,提问作者Shafi Khan

