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
asked Sep 23, 2016 at 0:47
Hari Babu
2442 gold badges3 silver badges11 bronze badges
-
Stack Overflow is not a code writing service.zero298– zero2982016年09月23日 01:24:22 +00:00Commented Sep 23, 2016 at 1:24
-
Sorry bro i was asking advice.. mr zero... you may not answer if you dont wish...Hari Babu– Hari Babu2016年09月23日 01:35:16 +00:00Commented Sep 23, 2016 at 1:35
-
I suggest you try to generate more of the sequence by hand. Start to look for patterns. Then describe in words the steps you need to take to solve the problem.Code-Apprentice– Code-Apprentice2018年06月12日 19:11:31 +00:00Commented Jun 12, 2018 at 19:11
1 Answer 1
I would recommend using a Collection 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) {
Deque<Integer> list = new ArrayDeque<>(dice);
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, Deque<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.addLast(i); // choose
diceRoll(dice - 1, numberOfDice, list); // explore
list.removeLast(); // un-choose
}
}
}
Bax
4,5265 gold badges47 silver badges70 bronze badges
lang-java