hey i'm trying to generate numbers from 1 to 3 in a way such that

number 1 has the probability 70% being generated
number 2 has the probability of 20% of being generated
number 3 has the probability of 10% of being generated

how do i do that?? can anyone please help.

Random r=new Random();
int i=1+r.nextInt(3);

this doesn't take into account the probabilities and generates the numbers in a random way..i need to generate the numbers according to their probabilites of being generated

Recommended Answers

All 5 Replies

generate a number between 1 and 10, then use an if statement to check which number was generated

gen < 7 
    gen = 1;
gen < 9
    gen = 2;
gen == 9
    gen = 3;

@sirlink99: good, but should line 5 of your pseudocode not read else instead of gen == 9?

It wouldn't matter, since the Random class return a number between 0(inclusive) and specified number (in this case 10)(exclusive). I would put it as gen == 9 just incase someone didn't know this(or programmed it wrong), and then place an else saying that "The generated number " + gen + " does not fit into any of the above ifs". This way the programmer would know something was wrong with the generated number before they realized that the probabilities were sqewed.

@sirlink99: OK I fully agree. But I just found it a little weird the way you wrote it. :)

hey thanks..i think this will work for me

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.