Random Numbers help

I am trying to generate a random number between 1 and 100, so I used the following:

Random r = new Random();

int num = r.nextInt(100);

However, I want to make the numbers a little less random.

I want numbers between 20 and 80 to be generated 90% of the time, and the remaining 10% of the time, the other numbers can be generated. So basically, on average, every 10 numbers generated, 9 of them will be between 20 and 80, and only 1 of them will be above or below these values.

Is this possible to do in a fairly simple and easy to understand way?

[583 byte] By [DamianY2J] at [2007-9-30 22:07:27]
# 1

Random gen;

[...]

gen= new Random();

[...]

public int nextNumber()

{

int num = gen.nextInt(10);

if(num==0) //10% of the time

{

int val=gen.nextInt(40);

if(val<20)

return val; // 0 to 19

else

return val+60; // 20 to 39 + 60 -> 80 to 99

}

else //90% of the time

{

return gen.nextInt(60)+20; //0 to 59 + 20 -> 20 to 79

}

}

oNyx at 2007-7-7 11:20:33 > top of Java-index,Other Topics,Java Game Development...
# 2
Thanks :-)
DamianY2J at 2007-7-7 11:20:33 > top of Java-index,Other Topics,Java Game Development...
# 3
You may also want to take a look at nextGaussian.
paulcw at 2007-7-7 11:20:33 > top of Java-index,Other Topics,Java Game Development...