【问题标题】:Check if multiple elements in an array contain the same value检查数组中的多个元素是否包含相同的值
【发布时间】:2019-04-27 13:16:41
【问题描述】:

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

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

现在,为了简单起见,我想问一下我如何才能知道是否有一个实例中的三个。

【问题讨论】:

  • int[] dice=new dice [5] 不确定这是否编译
  • @HanjunChen 在我的原始代码中,我将骰子作为一个类,因此我的数组就像这样(public Dice[] dices = new Dice[5];),这就是为什么我犯了这个非常小的错误写问题。然而,你在问题中看到的唯一一件事就是这个!真的很有帮助

标签: c# arrays algorithm random


【解决方案1】:

使用IDictionary&lt;int,int&gt;

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();

【讨论】:

    【解决方案2】:
        // 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);
    

    【讨论】:

      【解决方案3】:

      给出一个完全不同的方法,而不是:

      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?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-24
        • 2012-08-21
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 2016-10-13
        • 2018-06-15
        相关资源
        最近更新 更多