1

For instance I have an array that gets filled with random numbers and am going to call this one dice.

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

Now for the sake of simplicity I wanna ask how can I find out if got a three of a kind of instance.

Abdul SH
  • 67
  • 7
  • `int[] dice=new dice [5] ` not sure if this compiles – Hanjun Chen Nov 25 '18 at 22:17
  • @HanjunChen Well in my original code I have dice as a class therefore my array was like so (public Dice[] dices = new Dice[5];) and that's why I made this VERY MINOR mistake writing the questions. Yet the ONLY thing you've seen in the questions is this! So helpful really – Abdul SH Nov 26 '18 at 21:57

3 Answers3

2

use a 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]++;

(optional) you can use Linq to get the numbers that appear multiple times

var duplicates = dict.Where( x=>x.Value > 1 )
  .Select(x=>x.Key)
  .ToList();
Hanjun Chen
  • 544
  • 4
  • 11
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);
Waescher
  • 5,361
  • 3
  • 34
  • 51
0

To give a completely different approach, instead of:

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

Try this:

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

Of course you can combine both....

Do note that this works for a really specific rule engine, optimized for counting events.

If you really want a card/dice game, you'll need to rethink the rule engine to coupe with rules like "is it: 1,2,3,4,5,6, and in that order?".

For that, try: How to implement a rule engine?

Stefan
  • 17,448
  • 11
  • 60
  • 79