Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rock, Paper, Scissors. Determine win/loss/tie using math?

Tags:

math

logic

puzzle

So I was writing a rock paper scissors game when I came to writing this function:

a is player one's move, b is player two's move. All I need to figure out is if player one won, lost, or tied.

//rock=0, paper=1, scissors=2
processMove(a, b) {
    if(a == b) ties++;
    else {
             if(a==0 && b==2) wins++;
        else if(a==0 && b==1) losses++;
        else if(a==1 && b==2) losses++;
        else if(a==1 && b==0) wins++;
        else if(a==2 && b==1) wins++;
        else if(a==2 && b==0) losses++;
    }
}

My question is: What's the most elegant way this function can be written?

Edit: I'm looking for a one-liner.

like image 580
Farzher Avatar asked Jul 07 '12 17:07

Farzher


1 Answers

if (a == b) ties++;
else if ((a - b) % 3 == 1) wins++;
else losses++;

I need to know exactly which language you are using to turn it into a strictly one-liner...

For JavaScript (or other languages with strange Modulus) use:

if (a == b) ties++;
else if ((a - b + 3) % 3 == 1) wins++;
else losses++;
like image 183
user1494736 Avatar answered Sep 19 '22 13:09

user1494736