例如,我有一个数组,它会被随机数填充,并将这个称为骰子。
Random rnd = new Random()
int[] dice=new int [5]
for (int i=0;i<dice.length;i++)
{
dice[i]= rnd.next(1,7)
}现在,为了简单起见,我想问一问,如何才能找出是否有三个实例。
发布于 2018-11-25 22:21:59
使用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();发布于 2018-11-25 21:06:40
// 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);发布于 2018-11-25 21:00:55
给出一个完全不同的方法,而不是:
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,并按照这个顺序吗?”
https://stackoverflow.com/questions/53471881
复制相似问题