[英]Check if multiple elements in an array contain the same value
例如,我有一個填充有隨機數的數組,並將其稱為一個骰子。
Random rnd = new Random()
int[] dice=new int [5]
for (int i=0;i<dice.length;i++)
{
dice[i]= rnd.next(1,7)
}
現在,為了簡單起見,我想問一下如何找出一個實例中的三個實例。
使用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();
// 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);
提供一種完全不同的方法,而不是:
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並按此順序排列?”之類的規則。 。
為此,請嘗試: 如何實現規則引擎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.