-1

我不知道如何测试 5 个随机生成的数字是否相同。到目前为止,我所拥有的只是它们的创造。

dice1 = rand.Next(1,7);

dice2 = rand.Next(1,7);

dice3 = rand.Next(1,7);

dice4 = rand.Next(1,7);

dice5 = rand.Next(1,7);
4

8 回答 8

8

您可以这样做来生成 5 个随机掷骰子:

var dice = (from i in Enumerable.Range(0, 5) select rand.Next(1, 7)).ToArray();

或流利的语法:

var dice = Enumerable.Range(0, 5).Select(i => rand.Next(1, 7)).ToArray();

这是为了检查它们的相等性:

var first = dice.First(); // or dice[0];
var areSame = dice.Skip(1).All(d => d == first);
于 2013-05-06T22:11:27.153 回答
2
if(dice1 == dice2 && dice2 == dice3 && dice3 == dice4 && dice4 == dice5) {
  // scream at the random number generator
} else {

}
于 2013-05-06T22:12:07.170 回答
1

编辑,我的第一个答案脑子放屁。

如果足够容易,您可以进行某种嵌套:

if ((dice1 == dice2)&&(dice2 == dice3)&&(dice3 == dice4)&&(dice4 == dice5))

这应该工作

于 2013-05-06T22:10:09.523 回答
1
if(dice1 == dice2)
    if(dice2 == dice3)
        if(dice3 == dice4)
            if(dice4 == dice5)
                //do something...

可能是一种更漂亮的方式,但这会奏效

于 2013-05-06T22:10:46.913 回答
1

将它们放入 a 中HashSet,然后检查大小是否相同

var dice = Enumerable.Range(0, 5).Select(i => rand.Next(1, 7)).ToArray();
var set = new HashSet<int>(dice);
bool areSame = set.Count == 1; //1 unique value means they are all the same.
于 2013-05-07T00:13:05.630 回答
1
var result = new int[7];
result[dice1]++;
result[dice2]++;
result[dice3]++;
result[dice4]++;
result[dice5]++;
results.Any(x=>x==5);
于 2013-05-06T22:12:20.417 回答
0

首先,我建议把你的骰子变成可枚举的东西。PSWG 发布了一种非常优雅的方式来做到这一点,我有点嫉妒我不会想到它。这就是我的想法:

        var dice = new List<int>();
        for (int i = 0; i < 5; i++)
        {
            dice.Add(rand.Next(1, 7));
        }

然后您可以使用简单的评估来确定集合中的所有数字是否相同。我喜欢这个:

        // if all the dice rolled the same, do something
        if (dice.Distinct().Count() == 1)
        {

        }
于 2013-05-06T23:38:54.287 回答
0

你可以使用这样的方法:

public static bool AllEqual(params int[] values)
{
    foreach (var value in values)
        if (values[0] != value)
            return false;
    return true;
}

并像这样使用它:

bool allSame = AllEqual(dice1, dice2, dice3, dice4, dice5);

但是,正如 pswg 所示,在一个可枚举元素中生成所有骰子可能会更好。

于 2013-05-06T22:27:22.180 回答