Decide the winner of rock-paper-scissors for any two moves without listing all nine combinations.
Solution
main.c
#include <stdio.h>
enum move { ROCK, PAPER, SCISSORS };
static const char *names[] = {"rock", "paper", "scissors"};
const char *winner(enum move a, enum move b) {
if (a == b)
return "draw";
return (a - b + 3) % 3 == 1 ? "player 1" : "player 2"; /* each move beats the one before it */
}
int main(void) {
enum move games[][2] = {{ROCK, SCISSORS}, {ROCK, PAPER}, {PAPER, PAPER}, {SCISSORS, PAPER}};
for (int i = 0; i < 4; i++)
printf("%s vs %s: %s\n", names[games[i][0]], names[games[i][1]], winner(games[i][0], games[i][1]));
return 0;
}
Output Verified by compiling and running
rock vs scissors: player 1
rock vs paper: player 2
paper vs paper: draw
scissors vs paper: player 1
Ordered rock, paper, scissors, each move beats the previous one in a circle, so (a − b + 3) % 3 is 1 exactly when a wins. Arithmetic replaces a 9-case decision table.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!