views:

337

answers:

1

So I am writing a simple Rock, Paper, Scissors game in C (it's for an assignment by the way, though the main thing is to learn sockets. Also, I suspect it will be due before I get a good answer). I have it setup as Rock=0, Paper=1, and Scissors=2. Is there an easy one-liner to determine who wins? I tried playing around with it on paper, but I couldn't figure out any patterns.

+38  A: 
winner = (3 + player1 - player2) % 3;

This will give 1 if player 1 wins, 2 if player 2 wins, 0 for a tie.

Explanation: In the sequence Rock=0, Paper=1, Scissors=2, each item defeats the preceding one. This is true even if we treat the sequence as wrapping (that is, the last item precedes the first).

To put this in more mathematical terms, for any item X:

  • X is defeated by (X+1) % 3.
  • X defeats (X+2) % 3.

From this, it can be shown that (3+X-Y) % 3 is 1 if X defeats Y, or 2 if Y defeats X.

Adding 3 is needed to force the result to be non-negative: The modulus of a negative number will be negative or zero in C99 and implementation-dependent in C89.

interjay
This is brilliant, but such a one-liner needs at least 3 lines of documentation.
Georg
+1 Put me in a room with two monkeys and three type writers for all of eternity and we would never come up with that!!!
David Relihan
I think that c has this kind of construct:`(3 + player1 - player2) % 3 == 1 ? winner="player1" : (3 + player1 - player2) % 3 == 2? winner="player2" : winner="everyone";`
sixtyfootersdude
Dang! I thought it might be a modulus, but I made a mistake when I wrote out the table of who wins and it didn't look like it did. Anyway, +1 for the tip to add 3, which I wouldn't have known about.
asmeurer
this is a great answer, except that it is for someone's homework!
akf
@akf: According to the question, this is just a minor part of the homework, so it's not like I solved someone's assignment for them. Plus, I doubt that the assignment actually required that this be done in a one-liner.
interjay
@afk, we are allowed to use snippets from other sources, as long as we source them. And yes, it was far from the hardest part of the assignment!Also, I just realized that rand() % 3 would have been equivalent (i.e., it doesn't matter if the computer picks rock, paper, or scissors, or if it just randomly chooses win, lose, or tie :).
asmeurer