Just to make the comparison, I've put your approach next to this one.
public class Test {
private static int min = 0;
private static int max = 3;
private static Map<Integer, Integer> count = new HashMap<>();
public static void main(String[] args) {
OptionOne();
System.out.println("Option One: ");
for (Entry<Integer, Integer> entry : count.entrySet()) {
System.out.println(entry.getKey() + "\t " + entry.getValue());
}
count = new HashMap<Integer, Integer>();
OptionTwo();
System.out.println("\nOption Two:");
for (Entry<Integer, Integer> entry : count.entrySet()) {
System.out.println(entry.getKey() + "\t " + entry.getValue());
}
}
private static void OptionOne() {
for (int i = 0; i < 800000; i++) {
int number = min + (int) (Math.random() * ((max - min) + 1));
if (count.containsKey(number)) {
int sofar = count.get(number) + 1;
count.put(number, sofar);
} else {
count.put(number, 1);
}
}
}
private static void OptionTwo() {
for (int i = 0; i < 800000; i++) {
int number = (int) (Math.random() * 4);
if (count.containsKey(number)) {
int sofar = count.get(number) + 1;
count.put(number, sofar);
} else {
count.put(number, 1);
}
}
}
Output:
Option One:
0 199853
1 200118
2 200136
3 199893
Option Two:
0 199857
1 200214
2 199488
3 200441
Conclusion: your method works. Maybe your sample size wasn't enough?