Hari Babu Hari Babu - 2 months ago 9
Java Question

Generate possible values for dice rolls

I need a program in java that is capable to generate all possible combination of a dice roll. The number of dice as well as faces in dice may vary.
for example.
A combination of 3 six faced dice may be as follows.
111
112
113
114
115
116
121
122
123
124
125
126... and so on.... until 666.
any help???
some kind of

public Map generatePossibleNumbers(int face, int numberOfDice){
// generate numbers and return map
Map generatedMap=new HashMap();
return generatedMap;
}


Thanks in advance

Answer

I would recommend using an ArrayList instead of a Map since you are not going to need to store Key-Value pairs.

This is what I came up with:

public static void diceRoll(int dice, int numberOfDice) {
    List<Integer> list = new ArrayList<Integer>();
    diceRoll(dice, numberOfDice, list); // initially we have chosen nothing
}

// Private recursive helper method to implement diceRoll method.
// Adds a 'list' parameter of a list representing
private static void diceRoll(int dice, int numberOfDice, List<Integer> list) {
    if (dice == 0) {
        // Base Case: nothing left to roll. Print all of the outcomes.
        System.out.println(list);
    } else {
        // Recursive case: dice >= 1.
        for (int i = 1; i <= numberOfDice; i++) {
            list.add(i); // choose
            diceRoll(dice - 1, numberOfDice, list); // explore
            list.remove(list.size() - 1); // un-choose
        }
    }
}