Search code examples
javaalgorithmrandomdice

Resolve this java algorithm for Dice for Risk game


like in risk game I have to roll dices, but I don't want to use the Random.nextInt() method for each roll. For some reasons I have already the result of the attack, and I want to simply generate the values of the dices.

In risk game the dices are ordered and compared singly:
For example: if attack rolls 3 dices and defense rolls 2 dices and these are the results:
[4, 3, 5] - [3, 5]
The attack lost 1 tank and the defense lost 1 tanks because:
[5, 4, 3] - [5, 3]
5 = 5 (the attack loses in case of a tie)
4 > 3 (the defense loses)
3 (the third dice is useless in this case)

This is the input code:

int diceForAttack = StringUtils.nextInt(3) + 1;
int diceForDefense = StringUtils.nextInt(3) + 1;
//prints: attack Vs. defense
System.out.println(String.format("%d Vs. %d", diceForAttack, diceForDefense));

int maxLost = Math.min(diceForAttack, diceForDefense);
int attackLoses = StringUtils.nextInt(maxLost + 1);
int defenseLoses = maxLost - attackLoses;
//prints:
//Attack lost x
//Defense lost y
System.out.println(String.format("Attack lost %d\nDefense lost %d", attackLoses, defenseLoses));

//Now I want to generate two arrays
//such that the dice respect the values attackLoses and defenseLoses
int[] attack = new int[diceForAttack];
int[] defense= new int[diceForDefense];
...
...
...


The question is:
Since I already know how many tanks will lose the attack and the defense.
How can I generate two arrays such that the dice respect the values attackLoses and defenseLoses?


Solution

  • A clean, easy way to handle problems like this is to reroll the dice until you get the outcome that you want. The downside is that, if the requested outcome is unlikely (or even impossible), then it will take a while, but that seems as though it wouldn't be an issue here.