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

允我心安 提交于 2020-06-14 06:22:05

问题


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.


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



回答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.)




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



回答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;
};



回答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");
 }


来源:https://stackoverflow.com/questions/11377117/rock-paper-scissors-determine-win-loss-tie-using-math

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!