Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner to determine who wins in Rock, Paper, Scissors

Tags:

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.

like image 804
asmeurer Avatar asked May 08 '10 19:05

asmeurer


People also ask

How do you know who wins rock-paper-scissors?

The ancient Chinese game of rock-paper-scissors is governed by three simple rules: rock beats scissors, scissors beats paper, paper beats rock. On the face of it, the chances of winning are just one in three, but that presumes people pick rock, paper or scissors at random.

What do you say at the end of rock-paper-scissors?

The World Rock Paper Scissors Society's international standards on priming mandate “rock, paper, scissors, shoot,” with the delivery on shoot. You can see that here, and you'll see it in most internationally sanctioned tournaments.

Does rock-paper-scissors have a strategy?

The best strategy for rock paper scissors is to truly act randomly. This means playing each option about one-third of the time, ensures an opponent can't guess what's next.


1 Answers

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.

like image 163
interjay Avatar answered Oct 15 '22 09:10

interjay