I am using the following method which works but wondering if there is a better algorithm to perform the test. Is there a better way to do it? Doing this in C# but putting syntax
if ((ComputerIn) % 3 + 1 == userInput)
return "Win";
else if ((userInput) % 3 + 1 == ComputerIn)
return "Lose"
else
return "Draw"
If you wrap 3 around to 1 (using %) then the winner is always 1 greater than the loser.
This approach is more natural when you use 0-2, in which case we would use (ComputerIn+1)%3
. I came up with my answer by subbing ComputerIn
with ComputerIn-1
and UserInput
with UserInput-1
and simplifying the expression.
Edit, looking at this question after a long time. As written, if the ComputerIn
is not used anywhere else, and is only used to determine win/lose/draw, then this method is actually equivalent to:
if (ComputerIn == 1)
return "Win";
else if (ComputerIn == 2)
return "Lose"
else
return "Draw"
This can even be further simplified to
return new String[]{"Win", "Lose", "Draw"}[ComputerIn-1];
The results from this are entirely indistinguishable. Unless the randomly generated number is exposed to outside of this method. No matter what your input is, there's always 1/3 chance of all possibilities. That is, what you're asking for, is just a complicated way of returning "Win", "Lose", or "Draw" with equal probability.