剪纸石的算法

时间:2013-11-28 16:55:37

标签: c# java algorithm

我正在使用以下方法,但是想知道是否有更好的算法来执行测试。有没有更好的方法呢?在C#中执行此操作但将语法放在一边,相信在OOP语言中算法将是相同的。谢谢。

public String play(int userInput)
        {   //ComputerIn is a randomly generated number between 1-3
            ComputerIn = computerInput();

            if (ComputerIn == userInput)
                return "Draw";

            else if (ComputerIn == 1 && userInput == 2)
                return "Win";

            else if (ComputerIn == 2 && userInput == 3)
                return "Win";

            else if (ComputerIn == 3 && userInput == 1)
                return "Win";

            else if (ComputerIn == 1 && userInput == 3)
                return "Lose";

            else if (ComputerIn == 2 && userInput == 1)
                return "Lose";

            else
                return "Lose";
        }

8 个答案:

答案 0 :(得分:11)

if ((ComputerIn) % 3 + 1 == userInput)
    return "Win";
else if ((userInput) % 3 + 1 == ComputerIn)
    return "Lose"
else
    return "Draw"

如果你将3换成1(使用%),那么胜利者总是比失败者大1。

当你使用0-2时,这种方法更自然,在这种情况下我们会使用(ComputerIn+1)%3。我提出了我的答案,将ComputerInComputerIn-1UserInputUserInput-1相对应,并简化了表达。

编辑,经过很长时间看这个问题。如上所述,如果ComputerIn未在其他任何地方使用,并且仅用于确定赢/输/抽奖,那么此方法实际上等同于:

if (ComputerIn == 1)
    return "Win";
else if (ComputerIn == 2)
    return "Lose"
else
    return "Draw"

这甚至可以进一步简化为

return new String[]{"Win", "Lose", "Draw"}[ComputerIn-1];

这一结果完全无法区分。除非随机生成的数字暴露在此方法之外。无论你的输入是什么,所有可能性总是有1/3的可能性。也就是说,你所要求的只是一种以相同概率返回“胜利”,“失败”或“平局”的复杂方式。

答案 1 :(得分:2)

这是许多可能的解决方案之一。这将打印Win。

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      Input userInput = Input.Rock;
      Result result = Play(userInput);
      Console.WriteLine(Enum.GetName(result.GetType(), result));
      Console.ReadKey();
    }

    static Result Play(Input userInput)
    {
      Input computer = Input.Scissors;

      switch (userInput)
      {
        case Input.Paper:
          switch (computer)
          {
            case Input.Paper: return Result.Draw;
            case Input.Rock: return Result.Win;
            case Input.Scissors: return Result.Lose;
            default: throw new Exception("Logic fail.");
          }
        case Input.Rock:
          switch (computer)
          {
            case Input.Paper: return Result.Lose;
            case Input.Rock: return Result.Draw;
            case Input.Scissors: return Result.Win;
            default: throw new Exception("Logic fail.");
          }
        case Input.Scissors:
          switch (computer)
          {
            case Input.Paper: return Result.Win;
            case Input.Rock: return Result.Lose;
            case Input.Scissors: return Result.Draw;
            default: throw new Exception("Logic fail.");
          }
        default: throw new Exception("Logic fail.");
      }
    }
  }
  enum Input
  {
    Rock,
    Paper,
    Scissors
  }
  enum Result
  {
    Lose,
    Draw,
    Win
  }
}

答案 2 :(得分:1)

我就是这样做的:

public class Program
{

    public enum RPSPlay { Rock, Scissors, Paper }
    public enum RPSPlayResult { Win, Draw, Loose }

    public static readonly int SIZE = Enum.GetValues(typeof(RPSPlay)).Length;

    static RPSPlayResult Beats(RPSPlay play, RPSPlay otherPlay)
    {
        if (play == otherPlay) return RPSPlayResult.Draw;
        return ((int)play + 1) % SIZE == (int)otherPlay 
            ? RPSPlayResult.Win 
            : RPSPlayResult.Loose;
    }

    static void Main(string[] args)
    {
        Random rand = new Random();
        while (true)
        {
            Console.Write("Your play ({0}) (q to exit) : ", string.Join(",", Enum.GetNames(typeof(RPSPlay))));
            var line = Console.ReadLine();
            if (line.Equals("q", StringComparison.OrdinalIgnoreCase))
                return;
            RPSPlay play;
            if (!Enum.TryParse(line, true, out play))
            {
                Console.WriteLine("Invalid Input");
                continue;
            }
            RPSPlay computerPlay = (RPSPlay)rand.Next(SIZE);
            Console.WriteLine("Computer Played {0}", computerPlay);
            Console.WriteLine(Beats(play, computerPlay));
            Console.WriteLine();
        }
    }
}

答案 3 :(得分:1)

我更愿意使用静态3x3矩阵来存储可能的结果。但这是一个品味问题,我是一名数学家。

答案 4 :(得分:0)

这是我们在午餐时间创建的单行班。

using System;

public class Rps {
  public enum PlayerChoice { Rock, Paper, Scissors };
  public enum Result { Draw, FirstWin, FirstLose};

  public static Result Match(PlayerChoice player1, PlayerChoice player2) {
    return (Result)((player1 - player2 + 3) % 3);
  }

  public static void Main() {
    Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Rock), Result.Draw);
    Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Paper), Result.Draw);
    Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Scissors), Result.Draw);

    Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Scissors), Result.FirstWin);
    Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Paper), Result.FirstLose);

    Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Rock), Result.FirstWin);
    Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Scissors), Result.FirstLose);

    Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Paper), Result.FirstWin);
    Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Rock), Result.FirstLose);
  }

  public static void Test(Result sample, Result origin) {
    Console.WriteLine(sample == origin);
  }      
}

答案 5 :(得分:0)

\从Java初学者的角度来看。用户将计算机玩到无限远。

import java.util.Scanner;

public class AlgorithmDevelopmentRockPaperScissors{
    public static void main(String[] args){

        System.out.println("\n\nHello Eric today we are going to play a game.");
        System.out.println("Its called Rock Paper Scissors.");
        System.out.println("All you have to do is input the following");
        System.out.println("\n  1 For Rock");
        System.out.println("\n        2 For Paper");
        System.out.println("\n        3 For Scissors");

        int loop;
        loop = 0;

        while (loop == 0){
            System.out.println("\n\nWhat do you choose ?");


        int userInput;
        Scanner input = new Scanner(System.in);
        userInput = input.nextInt();

        while (userInput > 3 || userInput <= 0 ){ //ensure that the number input by the sure is within range 1-3. if else the loop trap.

            System.out.println("Your choice "+userInput+" is not among the choices that are given. Please enter again.");
            userInput = input.nextInt();
        }



        switch (userInput){
            case 1:
            System.out.println("You Chose Rock.");
            break;

            case 2:
            System.out.println("You Chose Paper.");
            break;

            case 3:
            System.out.println("You Chose Scissors");
            break;

            default:
            System.out.println("Please Choose either of the choices given");
            break;

        }



        int compInput;
        compInput = (int)(3*Math.random()+1);

        switch (compInput){
            case 1:
            System.out.println("\nComputer Chooses Rock.");
            break;

            case 2:
            System.out.println("\nComputer Chooses Paper.");
            break;

            case 3:
            System.out.println("\nComputer Chooses Scissors");
            break;

        }

        if (userInput == compInput){

            System.out.println(".........................................");
            System.out.println("\nYou Both chose the same thing, the game ends DRAW.");
            System.out.println(".........................................");
        }

        if (userInput == 1 && compInput == 2){

            System.out.println(".........................................");
            System.out.println("\nComputer wins because Paper wraps rock.");
            System.out.println(".........................................");
        }

        if (userInput == 1 && compInput == 3){

            System.out.println(".........................................");
            System.out.println("\nYou win because Rock breaks Scissors.");
            System.out.println(".........................................");
        }

        if (userInput == 2 && compInput == 1){

            System.out.println(".........................................");
            System.out.println("\nYou win Because Paper wraps Rock");
            System.out.println(".........................................");
        }

        if (userInput == 2 && compInput == 3){

            System.out.println(".........................................");
            System.out.println("\nComputer wins because Scissors cut the paper");
            System.out.println(".........................................");
        }

        if (userInput == 3 && compInput == 1){

            System.out.println(".........................................");
            System.out.println("\nComputer Wins because Rock Breaks Scissors.");
            System.out.println(".........................................");
        }

        if (userInput == 3 && compInput == 2){

            System.out.println(".........................................");
            System.out.println("\nYou win because scissors cut the paper");
            System.out.println(".........................................");
        }

        }


    }

}

答案 6 :(得分:0)

使用正弦波函数计算结果的简单JavaScript实现:

<script>
    var tab = ["Lose","Draw","Win"];
    var dict = ["Paper","Stone","Scissors"];
    var i,text = '';
    for (i = 0; i < dict.length; i++) {
        text += i + '-' + dict[i] + ' ';
    }
    var val1 = parseInt(prompt(text));
    var val2 = Math.floor(Math.random() * 3);
    alert('Computer chose: ' + dict[val2]);
    result = Math.sin((val1*180+1) - (val2*180+1));
    alert(tab[Math.round(result)+1]);
</script>

不需要,只是为了好玩...

Check it

答案 7 :(得分:0)

观察:如果from django.contrib.auth.models import User User._meta.get_field('email')._unique = True User._meta.get_field('email').blank = False User._meta.get_field('email').null = False 仅比userInput领先(1,2,3,2),或落后2(3,1,2),则用户获胜)。

反之,如果computerInput落后userInput落后一,或者落后两个,则用户输了。

在模3中,滞后一与超前二相同。 (-1 mod 3 == 2 mod 3 == 2)

computerInput