One-liner to determine who wins in Rock, Paper, Scissors
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.
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.
精彩评论