检查数组中的多个元素是否包含相同的值

时间:2018-11-25 20:54:45

标签: c# arrays algorithm random

例如,我有一个填充有随机数的数组,并将其称为一个骰子。

Random rnd = new Random()
int[] dice=new int [5]
for (int i=0;i<dice.length;i++)
{
dice[i]= rnd.next(1,7)
}

现在,为了简单起见,我想问一下如何找出一个实例中的三个实例。

3 个答案:

答案 0 :(得分:2)

使用IDictionary<int,int>

var dict = new Dictionary<int,int>();
foreach (int i in dice)
    if(!dict.ContainsKey(i))
        dict.Add(i,1);
    else dict[i]++;

(可选),您可以使用Linq获取多次出现的数字

var duplicates = dict.Where( x=>x.Value > 1 )
  .Select(x=>x.Key)
  .ToList();

答案 1 :(得分:1)

    // preparation (basically your code)
    var rnd = new Random();
    var dice = new int[5];

    for (int i=0; i < dice.Length; i++)
    {
        dice[i]= rnd.Next(1,7);
    }

    // select dices, grouped by with their count
    var groupedByCount = dice.GroupBy(d => d, d => 1 /* each hit counts as 1 */);

    // show all dices with their count
    foreach (var g in groupedByCount)
        Console.WriteLine(g.Key + ": " + g.Count());

    // show the dices with 3 or more 
    foreach (var g in groupedByCount.Where(g => g.Count() >= 3))
        Console.WriteLine("3 times or more: " + g.Key);

答案 2 :(得分:0)

要提供一种完全不同的方法,而不是:

Random rnd = new Random();
int[] dice=new int[5];
for (int i=0;i<dice.length;i++)
{
    dice[i]= rnd.next(1,7);
}

尝试一下:

Random rnd = new Random();
int[] valueCount = new int[6];
for (int i=0; i<5; i++)
{
    valueCount[rnd.next(0,6)]++;
}

//you have kept track of each value.
if (valueCount.Any(c => c == 3))
    //3 of a kind

当然您可以将两者结合在一起。...

请注意,这适用于真正特定的规则引擎,已针对事件计数进行了优化。

如果您真的想玩纸牌/骰子游戏,则需要重新考虑规则引擎,以配合诸如“这样的规则:1,2,3,4,5,6,并按此顺序?”

为此,请尝试:How to implement a rule engine?

相关问题