1

I want to generate a random number with a given probability but I'm not sure how to:

I have a two dimensional array: int[ ][ ] aryNumbers = new int[4][]

and for each number(4) I want to generate a int result in a inteval of [1...9] with a prob of 0.5 .Otherwise a number in a interval of [10...99].

Note: I know how to generate a number, but choosing between intervals confused me.

Edit:

 public int numberAttribution(){
    Random rand = new Random();
    double dbNum = rand.nextDouble();
    int intNum;
    int min1 = 1, max1 = 9, range1 = max1 - min1 + 1;
    int min2 = 10, max2 = 99, range2 =  max2 - min2 + 1;

    if(dbNum < 0.5){
        intNum = rand.nextInt(range1) + min1;
    }else{
        intNum = rand.nextInt(range2) + min2;
    } 
       System.out.print(intNum);
    return intNum;
}
David Edgar
  • 477
  • 8
  • 23
  • 4
    Generate a random number between 0 and 1; if its value is less than 0.5, scale it to the range [1..9]; otherwise, scale it to the range [10..99]. – Andy Turner Sep 29 '15 at 13:32
  • you just need `Random#nextDouble` without parameter (creats a value between 0.0-1.0) an if statement and `Random#nextInt` – SomeJavaGuy Sep 29 '15 at 13:37
  • you can do `r.nextBoolean() ? r.nextInt(9) + 1 : r.nextInt(90) + 10` – Cinnam Sep 29 '15 at 13:47
  • This is what I have done: public int numberAttribution(){ Random rand = new Random(); double dbNum = rand.nextDouble(); int intNum; int min1 = 1, max1 = 9, range1 = max1 - min1 + 1; int min2 = 10, max2 = 99, range2 = max2 - min2 + 1; if(dbNum < 0.5){ intNum = rand.nextInt(range1) + min1; }else{ intNum = rand.nextInt(range2) + min2; } System.out.print(intNum); return intNum; } – David Edgar Sep 29 '15 at 13:52
  • @CyberAllien You don't need all that - the expression I posted above generates what you want – Cinnam Sep 29 '15 at 13:54
  • The more generic version of your problem is generating a weighed random number. See http://stackoverflow.com/questions/8435183/generate-a-weighted-random-number – Kafkaesque Sep 29 '15 at 13:57

2 Answers2

1

So if I got you right, you want a 50% chance to generate a number between 1 and 9, otherwise generate a number between 10 and 99?

In that case you could do it like this:

int randomNumber = 0;
if (Math.random() > 0.5) {
    randomNumber = 1 + (int) (Math.random() * 9);
} else {
    randomNumber = 10 + (int) (Math.random() * 90);
}

Runnable version

se1by
  • 108
  • 7
1

I assume this method will be called millions of times a second. In that case it might be wise to only generate one random each time:

  private static int generateRandom() {
    double rand = Math.random();
    if (rand < 0.5) {
      rand *= 18;
      rand += 1;
    } else {
      rand -= 0.5;
      rand *= 180;
      rand += 10;
    }
    return (int) rand;
  }
Andreas
  • 4,937
  • 2
  • 25
  • 35