gpt4 book ai didi

c# - 有没有没有if/else/switch/的公式?等可以取代解决方案[,]矩阵

转载 作者:行者123 更新时间:2023-11-30 22:44:00 24 4
gpt4 key购买 nike

有没有没有if/else/switch/的公式?等可以取代解决方案 [,] 矩阵,这对性能/效率有何影响或差异?

     class Program
{
private static Random r = new Random();
// names of the "moves"
private static string[] rps = { "PAPER", "ROCK", "SCISSORS"};
// result feedback string to be formatted
private static string[] feedback = { "{1} Beats {0}, You Loose!","{0} Equals {1}, Draw!", "{0} Beats {1}, You Win!" };
// solution matrix ( 0 = loose ; 1 = draw ; 2 = win // array1: for paper; array2: for rock; array3: for scissors; )
private static int[,] solution = {{1, 2, 0},{0, 1, 2},{2, 0, 1}};

/// <summary>
/// Rock Paper scissors solution w/o calculation or if/case/else/
/// </summary>
/// <param name="args">dummy.</param>
static void Main(string[] args)
{
// simulate the players move
int player = r.Next(3);

// simulate the computers move
int computer = r.Next(3);

// retrieve the result from the matrix
int result = solution[player, computer];

//write the result of the match
Console.WriteLine(String.Format("you : {0} vs {1} : computer", rps[player], rps[computer]));
Console.WriteLine(String.Format(feedback[result], rps[player], rps[computer]));

}
}

最佳答案

是的,有一个非常简单的公式:

player computer  solution  (c+4-p)%3
0 0 1 1
0 1 2 2
0 2 0 0
1 0 0 0
1 1 1 1
1 2 2 2
2 0 2 2
2 1 0 0
2 2 1 1

所以你可以使用:

int result = (computer + 4 - player) % 3;

访问数组和计算值的时间大致相同。但是,此应用程序的性能差异可以忽略不计。仅将结果写入控制台比使用数组或计算值要花费更长的时间。当然,通过计算您不需要数组的值,但因为它太小了,所以没有太大区别。

还要考虑解决方案的可读性。该公式与您使用它的目的没有逻辑联系,它只是获得特定结果的一种手段,因此您需要大量注释来解释它的作用...

编辑:

如果你想关注可读性,你可以将逻辑放在一个单独的类中:

public class Play {

public enum Value { Paper = 0, Rock = 1, Scissors = 2 }

private Value _value;

public Play(Random rnd) {
_value = (Value)rnd.Next(3);
}

public bool SameAs(Play other) {
return _value == other._value;
}

public bool Beats(Play other) {
return
(_value == Value.Paper && other._value == Value.Rock) ||
(_value == Value.Rock && other._value == Value.Scissors) ||
(_value == Value.Scissors && other._value == Value.Paper);
}

public override string ToString() {
switch (_value) {
case Value.Paper: return "PAPER";
case Value.Rock: return "ROCK";
default: return "SCISSORS";
}
}

}

现在逻辑变得更清晰了:

Random r = new Random();

Play player = new Play(r);
Play computer = new Play(r);

Console.WriteLine("you : {0} vs {1} : computer", player, computer);

string feedback;
if (player.SameAs(computer)) {
feedback = "{0} Equals {1}, Draw!";
} else if (player.Beats(computer)) {
feedback = "{0} Beats {1}, You Win!";
} else {
feedback = "{1} Beats {0}, You Loose!";
}

Console.WriteLine(feedback, player, computer);

关于c# - 有没有没有if/else/switch/的公式?等可以取代解决方案[,]矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3645594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com