Search code examples
c#randomdie

breaks while loop when all die rolls the same number


using System;
using System.Collections.Generic;
namespace AnyDice
{
    class Program
    {
        static void Main(string[] args)
        {
            int diceSides;
            int rollDie;
            int count = 0;
            bool keepRolling = true;
            List<int> num = new List<int>();
            Random random = new Random();

            Console.Write("Write the number of sides of your die: ");
            diceSides = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Type the numbers of the die");

            for (int i = 0; i < diceSides; i++)
            {
                int rank = 1 + i;
                Console.Write(rank + "~~> ");
                num.Add(Convert.ToInt32(Console.ReadLine()));
            }

            num.Sort();

            Console.WriteLine("\nHere's the die and its contents");
            for (int i = 0; i < num.Count; i++)
            {
                Console.Write("[");
                Console.Write(num[i]);
                Console.Write("]");
            }

            Console.WriteLine("\nHow many times do you want to roll at once");
            rollDie = Convert.ToInt32(Console.ReadLine());
            while (keepRolling)
            {
                for (int i = 0; i < rollDie; i++)
                {
                    Console.Write("[");
                    Console.Write(num[random.Next(num.Count)]);
                    Console.Write("]");
                    count++;
                }
                Console.ReadLine();
            }

            Console.WriteLine("It took you " + count + " attempts");

            Console.ReadLine();
        }
    }
}

For example if (4,4,4,4) is rolled or (2,2) in any "n" number of column the while loop breaks. I thought of storing each die rolled value in another arraylist and comparing each value in it. If its all equal then it breaks.. but I have no clue on how to implement it.


Solution

  • We have Linq. It lives in the System.Linq namespace and this might help you.

    I'll should two ways of checking if all die are the same:

    int first = dies.First();
    if (dies.All(i => i == first))
    {
      // break if all are equals to the first die
    }
    

    Or using Distinct we can filter out any copies.

    if (dies.Distinct().Count() == 1)
    {
      // if we only have unique items and the count is 1 every die is the same
    }