LearnFrenzy
Sign in Take a free test

Control Instructions · Decision Making Programs · Question 6

Rock, paper, scissors winner logic in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links