samedi 25 février 2017

Generating a random number with more middle values

I have been trying to find a way to generate a number which is more likely to generate a number in the middle of a range. Given:

rnum = r.nextInt(5) + 1;//+ 1 to exclude 0

generates a completely random number between 1 and 5(0 and 4 if + 1 is removed). What I want to do, is generate less of 1 and 5, and generate a lot of 3's. I attempted this:

int[] classes = {1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5};
System.out.println("Class " +  classes[r.nextInt(15)]);//logs the output

But it generates this:(print statement repeated 10 times)

Class 2
Class 3
Class 1
Class 4
Class 3
Class 4
Class 2
Class 3
Class 2
Class 5

However, this is neither efficient or a good way to do it. Further, because the random number generator used in retrieving the number is completely random instead of focusing on a center value, thus making the output above. 3 only appears 30% of the time, which is too low. 2 appears 30% of the time as well, which means (in this test) it has the same probability to be generated as 3.

So, how can I generate a number randomly with a higher probability to generate a number in the middle of a range?




Aucun commentaire:

Enregistrer un commentaire