# Problem in Finding the Mode of Dice Roll Outcomes? Help?

• 05-11-2011, 02:23 AM
Kratos321
Problem in Finding the Mode of Dice Roll Outcomes? Help?
Ok, so I wrote a program in "Ready to Program with JAVA Technology IDE" that generates and prints out a total of 50 numbers between 1 and 6 to simulate dice throw outcomes. I also used arrays to try and find the mode number as efficiently as possible, using the least amount of code.

THE PROBLEM: ok so the problem is that when there is more than one mode, only the mode with the largest dice index will be set to the most occuring number as it is the one processed last. So dice roll of 6 would be mode even though dice roll of 5 occured the same number of times.

So does anyone know how to fix this problem with the least amount of code. I tried but just couldn't find a way. This is what I have so far:

// The "DiceRoll" class.
import java.awt.*;
import hsa.Console;

public class DiceRoll
{
static Console c; // The output console

public static void main (String[] args)
{
c = new Console ();

int rollNumber, i=0;
int modeNumber, mode;

int[] num = new int[6];
for(i=0;i<6;i++){
num[i]=0;
}//end of for loop

for (i=0;i<50;i++) {

rollNumber = (int) (Math.random()*6)+1;
c.print(rollNumber+"\t");
num[rollNumber-1]++;

}//end of for loop

for (i=0;i<6;i++) {
c.println("\nNumber of "+(i+1)+"'s rolled: "+ num[i]);
}//end of for loop

modeNumber = num[0];
mode = 1;
for(int j=1; j<6; j++){
if (num[j]>modeNumber) {
modeNumber = num[j];
mode = j+1;
}
//if (num2l
}
c.println("\nThe mode is "+mode);

} // main method
} // DiceRoll class
• 05-11-2011, 02:38 AM
Junky
One way would be to iterate over the array to find the MAX value. Then iterate over the loop again and print out each number that has a count equal to MAX. That is slightly inefficient as you must iterate over the array twice.

Another method would be to have a StringBuilder/StringBuffer. Keep track of the MAX count and each number that has a count equal to MAX add it to the buffer. If a number has a count greater than MAX update max, delete all values from the buffer and add your new number to the buffer.

For example if you had: 1:4, 2:2, 3:4, 4:1, 5:7, 6:7
Store 4 in MAX
2 has a count less than MAX - ignore
3 has a count equal to MAX, add 3 to buffer
ignore 4
5 has a count greater than MAX, delete 1 and 3 from buffer, add 5 to buffer, update MAX
6 has a count equal to MAX, add 6 to buffer
Print out buffer
• 05-11-2011, 03:21 AM
Fubarable
Original poster -- please abide by the rules you agreed to on joining this forum and do not double post a question. Post it once in the best forum only.
• 05-11-2011, 09:07 PM
Kratos321
@ Junky. thanks alot I think I can use your idea.
@Fubarable. oh yeah sorry about that.