Match Result: Determining the Winner of a Match
This challenge focuses on implementing a function in Rust that determines the winner of a match based on a given set of rules. The function will take two player scores as input and return a Result type indicating either the winning player or a draw. This is a common pattern in Rust for handling outcomes that can be either successful (a winner) or unsuccessful (a draw).
Problem Description
You are tasked with creating a Rust function called determine_match_result that takes two integer arguments, player1_score and player2_score, representing the scores of two players in a match. The function should return a Result<String, String> where:
Ok(player_name)indicates that the player with the corresponding name won the match.player_namewill be either "Player 1" or "Player 2".Err("Draw")indicates that the match ended in a draw.
The rules for determining the winner are as follows:
- If
player1_scoreis strictly greater thanplayer2_score, then "Player 1" wins. - If
player2_scoreis strictly greater thanplayer1_score, then "Player 2" wins. - If
player1_scoreis equal toplayer2_score, then the match is a draw.
Examples
Example 1:
Input: player1_score = 5, player2_score = 3
Output: Ok("Player 1")
Explanation: Player 1's score (5) is greater than Player 2's score (3), so Player 1 wins.
Example 2:
Input: player1_score = 2, player2_score = 7
Output: Ok("Player 2")
Explanation: Player 2's score (7) is greater than Player 1's score (2), so Player 2 wins.
Example 3:
Input: player1_score = 4, player2_score = 4
Output: Err("Draw")
Explanation: Player 1's score (4) is equal to Player 2's score (4), so the match is a draw.
Example 4: (Edge Case - Negative Scores)
Input: player1_score = -1, player2_score = 0
Output: Ok("Player 2")
Explanation: Player 2's score (0) is greater than Player 1's score (-1), so Player 2 wins.
Constraints
player1_scoreandplayer2_scorewill be integers.- The scores can be positive, negative, or zero.
- The function must return a
Result<String, String>as specified. - The function should be efficient and handle all valid integer inputs.
Notes
Consider using a match statement to elegantly handle the different possible outcomes based on the comparison of the scores. Think about how to clearly represent the winning player's name within the Ok variant of the Result. The problem emphasizes using Result to represent the outcome, which is a core concept in Rust error handling.