The goal of the assignment is to use parallel 1-D arrays, but 2-D arrays are also allowed.
I can print out the different combinations such as 1,1 (otherwise known as snake eyes) rolled by the pair of dice.
Trying to print out the number of times each combination was rolled without printing the combination the same number of times it was rolled is difficult.
Ex:
Enter the number of times you want to roll a pair of dice: 5
You rolled: 1 and 5 a total of 1 times - What I don't want
You rolled: 4 and 3 a total of 1 times
You rolled: 1 and 5 a total of 2 times - For duplicates this is all I want to print
You rolled: 3 and 3 a total of 1 times
You rolled: 2 and 2 a total of 1 times
I know the loop for printing it out right after it increments the combo array (which holds the number of times each combination was rolled) is not correct, but I am stuck on how to modify it.
I consider combo[0][0] to be the number of times 1,1 is rolled, combo[0][1] to be the number of times 1,2 is rolled, and so on.
import java.util.Scanner;
public class Dice {
Scanner read = new Scanner(System.in);
Random diceRoll = new Random();
int numRolls;
int[] dice1 = new int [1000];
int[] dice2 = new int [1000];
int[][] combo = new int[6][6];
public void getRolls()
{
System.out.println("Enter the number of times you want to roll a pair of dice: ");
numRolls = read.nextInt();
dice1 = new int[numRolls];
dice2 = new int[numRolls];
for (int i = 0; i < dice1.length; i++)
{
dice1[i] = diceRoll.nextInt(6) + 1;
dice2[i] = diceRoll.nextInt(6) + 1;
}
System.out.println("\n");
for (int j = 0; j < combo.length; j++)
{
for (int k = 0; k < combo[0].length; k++)
{
combo[j][k] = 0;
}
}
for (int m = 0; m < numRolls; m++)
{
combo[dice1[m] - 1][dice2[m] - 1]++;
System.out.println("You rolled: " + dice1[m] + " and " +
dice2[m] + " a total of " + combo[dice1[m] - 1][dice2[m] - 1] +
" times");
}
Self-answer:
I made the printing loop separate from the combo calculation loop. If the combo value for the combination is 1, then I simply print it out stating it was rolled 1 time. If the combo value for the combination was greater than 1, I print it out at the first occurrence stating it was rolled that many times, then set the combo value for that combination equal to 0. Only combos with at least a combo value of 1 are printed, so duplicate lines cannot be printed (i.e. 1,1 rolled 4 times only prints on one line now instead of 4 separate lines).
for (int m = 0; m < numRolls; m++)
{
combo[dice1[m] - 1][dice2[m] - 1]++;
}
for (int m = 0; m < numRolls; m++)
{
if (combo[dice1[m] - 1][dice2[m] - 1] > 1)
{
System.out.println("You rolled: " + dice1[m] + " and " + dice2[m] + " a total of " + combo[dice1[m] - 1][dice2[m] - 1] + " time(s)");
combo[dice1[m] - 1][dice2[m] - 1] = 0;
}
if (combo[dice1[m] - 1][dice2[m] - 1] == 1)
{
System.out.println("You rolled: " + dice1[m] + " and " + dice2[m] + " a total of " + combo[dice1[m] - 1][dice2[m] - 1] + " time(s)");
}
}