Algorithm for scissor paper stone

前端 未结 8 616
日久生厌
日久生厌 2021-02-06 20:03

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

8条回答
  •  离开以前
    2021-02-06 20:33

    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.

提交回复
热议问题