-4

I need a function which generates me random numbers but where some numbers can appear more often then others.

Lets say i want random numbers from 1 to 10 where 2 and 3 have twice the chance to appear than the rest.

How can i do this in java? Haven`t found a function for this.

Edit: Code i have so far (Which was a compromise solution, i know it`s not what i want)

int min;
int max;
double min1;
double max1;
for(int j=0;j<Ammount_numbers;j++) {
            if(min1==0) {
                  min1= min + (Math.random() * (max+1-min));
                  max1= min + (Math.random() * (max+1-min));
            }

            double randomnumber = min1 + (Math.random() * ((max1-min1) + 1));
}

Min and Max are the borders (1 to 10 in the example) And with min1 and max1 i generated new, smaller borders so that the randomnumber is clustered in a random range.. And as i said: i know that this is not what i wanted, it was just a compromise solution so i could work with it..

Grogak
  • 27
  • 6

4 Answers4

0

To implement a generator of a discrete random variable with prescribed probabilities, a well-known technique is to fill an array with the cumulated probabilities. The values will fit in range [0,1].

Then perform uniform drawings and identify the subinterval where the value falls, by dichotomic search (linear can do for a small array).

The subinterval index will follow the desired distribution.

Yves Daoust
  • 53,540
  • 8
  • 41
  • 94
0

You can do like this Now there is a 50 % chance of getting a 2 or 3

a=(Math.random() * 7) + 4;
b=(Math.random() * 2 ) + 2; // math.random() within a range.
x=Math.random()* 1;
if(x==0){
// print a;
}
else if(x==1){
// print b;
}
Varen
  • 1
  • 3
  • i have just used the concept of Math.random() within the range. this is an excellent article on it https://stackoverflow.com/questions/7961788/math-random-explained – Varen Aug 19 '17 at 11:10
0

Set up the numbers you want at the correct frequencies in an array and pick a random entry from the array.

Random rand = new Random();

// ...

int specialRandom() {
  int[] selections = {1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10};
  return selections[rand.nextInt(selections.length)];
}

For more complex selection, use the desired frequency, pick a random frequency and return the matching number.

rossum
  • 14,876
  • 1
  • 21
  • 36
-1

You cannot do that with Math.random() itsself, but you could write your own random() method, which uses Math.random() and returns your own random numbers according to your own scale.

Dorian Gray
  • 2,781
  • 1
  • 8
  • 25