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

10,362

Solution 1

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++;

Solution 2

A 3x3 matrix would be "more elegant", I suppose.

char result = "TWLLTWWLT".charAt(a * 3 + b);

(Edited: Forgot that a and b were already zero-origin.)

Solution 3

I suppose you could use the terniary operator like this -

if (b==0) a==1? wins++ : loss++;

if (b==1) a==1? loss++ : wins++;

if (b==2) a==1? loss++ : wins++;

Solution 4

You can do it with a simple mathematical formula to get the result and then compare with if like this:

var moves = {
  'rock': 0, 
  'paper': 1,
  'scissors': 2
};
var result = {
  'wins': 0,
  'losses': 0,
  'ties': 0
};
var processMove = function (a, b) {
  var processResult = (3 + b - a) % 3;
  if (!processResult) {
    ++result['ties'];
  } else if(1 == processResult) {
    ++result['losses'];
  } else {
    ++result['wins'];
  }
  return result;
};

jsFiddle Demo


One line processMove function without return:

var processMove = function (a, b) {
  ((3 + b - a) % 3) ? 1 == ((3 + b - a) % 3) ? ++result.losses : ++result.wins : ++result.ties;
};

Solution 5

how do you do it in java?

result = (comp - x ) % 3 ;

System.out.println (result);
 if (result == 0 )// if the game is tie
 {
     System.out.println ("A Tie!") ;
 }

 else if (result == 1 || result == 2 )
 {
    //System.out.println (user + " " +   "beats" + " " + computer_choice + " you win" );
     System.out.println ("comp win");
 }

 else
 {
     System.out.println ("you win");
    //System.out.println (computer_choice  + " " +  "beats" + " " + user + "you lose");
 }
Share:
10,362
Farzher
Author by

Farzher

i.write(code);

Updated on June 08, 2022

Comments

  • Farzher
    Farzher almost 2 years

    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.

  • Farzher
    Farzher almost 12 years
    rock vs scissors doesn't work: (0 - 2 % 3) = -2. Using javascript
  • Tim
    Tim almost 12 years
    Looks like it's missing a pair of parenthesis: ((a-b) % 3 == 1). In C operators modulo is higher in order of operations than subtraction.