Search code examples
c#recursiondicerolling-computation

Creating a dice that doubles and continues to roll if it lands on a specific number in C#?


I am trying to make a program that I Believe has to make use of recursion. In short: create a program that will throw a Dice. If it lands on a 6, two Dices are created and rolled, and so on until no more 6 are rolled.

The problem is not creating a new or true random object, but the recursive Dices.

The recursion method looks like this:

    public static int Recursion(int a)
    {
        Random m = new Random();

        if (a < 6)
        {
            return a;
        }

        else
        {
            a = m.Next(1, 7);
            return Recursion(a) * 2;
        }
    }

Solution

  • Possibly something like this?

    public static int Roll() {
       return Roll(new Random(), 1);
    }
    
    public static int Roll(Random random, int diceCount) {
        int sum = 0;
        for (int dice = 1; dice <= diceCount; ++dice) {
            int rolled = random.Next(1, 7);
            if (rolled == 6) {
                sum += Roll(random, 2)
            }
            else
            {
                sum += rolled;
            }
    
        }
    
        return sum;
    }
    

    So, first I roll one die/dice. If it is not 6, then I accept its value as the result. If it is six, then I remove that die/dice, and replace it with two other I roll. Then, for each of the new ones I follow the same rule, until all the dice on the table is rolled and none of them is 6. Now I sum all the value of dice. This is what this recursive algorithm does. Note, that - however it has infinitely low chance - you can play this until the end of times, since there is always chance of rolling 6, so you can possibly roll only 6's until you die.