2

I've been searching for, and found similar topics, but cannot understand them or work out how to apply them.

Simple: all I want is to generate a number between 1 and 100:

  • Numbers 1 to 30 should have a 60% probability.
  • Numbers 31 to 60 should have a 35% probability.
  • Numbers 61 to 100 should have a 5% probability.
sstan
  • 35,425
  • 6
  • 48
  • 66
djohn316
  • 57
  • 7
  • 3
    What's the code you used to generate numbers? – Envil Jun 28 '15 at 01:42
  • 1
    possible duplicate of [Generate A Weighted Random Number](http://stackoverflow.com/questions/8435183/generate-a-weighted-random-number) –  Jun 28 '15 at 01:55

3 Answers3

1

Get numbers in your ranges

First generate 3 random numbers in your 3 intervals.

1: 1-30

2: 31-60

3: 61-100

Generate the probability number

Next, generate a number 1-100. If the number is 1-60 choose the first random number from the first step if it is 61-95 do the second option and if it is 96-100 chose the third.

J Blaz
  • 783
  • 1
  • 6
  • 26
1

This sounds like a homework problem so I will not provide the code, but here is a description of a simple algorithm:

Generate a random number between 1 and 100. Lets call this X. X will be used to determine how to generate your final result:

If X is between 1 and 60, generate a random number between 1 and 30 to be your final result.

If X is between 61 and 95, generate a random number between 31 and 60 to be your final result.

If X is between 96 and 100, generate a random number between 61 and 100 to be your final result.

You can see that this requires two random number generations for every weighted number that you want. It can actually be simplified into a single random number generation, and that is left as an exercise for you.

FYI, how to generate a random number within a range is found here: How do I generate random integers within a specific range in Java?

Community
  • 1
  • 1
Nicholas Smith
  • 975
  • 7
  • 18
  • Its actually not a homework problem, just a project im working on fro someone and I know how to generate ints in a range, I just wanted to check if their was an easier way to do it Thanks a lot though – djohn316 Jun 28 '15 at 02:05
0

Simplest way for me would be to generate four randoms. The first would be a number 1-100. The second would be a number 1-30, the third would be a number 31-60, and the fourth would be a number 61-100. Think of the first random as a percent. If it is 1-60 you then move on to run the second random, if it is 60-95 run the third random, and if it is 95-100 run the fourth random. There are other ways to make it shorter, but in my opinion this is easiest to comprehend.

Create random number 1-100 with this: (int)(Math.random()*100)+1 The rest should just be conditionals.

Kyle
  • 183
  • 1
  • 1
  • 12