1

I already know how to generate a random number within a range; but my question is about possibility of generating a number from a set of 2 or more specified numbers. for example: the output must be randomly chosen between exactly "1" or "3" or "100"

Another way to put it is: The value obtained will be any of the three numbers: 1, 3 or 100 (without any of the numbers in between).

pjs
  • 18,696
  • 4
  • 27
  • 56
Shervin4030
  • 27
  • 1
  • 9

4 Answers4

6
  • Put the numbers in an int[3]
  • Choose a random number between 0 & 2.
  • Use that random number as the index of the array.

..is one of many ways.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • simple and true; probably the best, tnx – Shervin4030 Dec 14 '13 at 16:58
  • Best solution if you want the outcomes with equal probabilities. – pjs Dec 14 '13 at 16:58
  • @pjs you dont mean that salihrkc's solution is not? given that the numbers are divided correctly. – Shervin4030 Dec 14 '13 at 17:03
  • 1
    @Shervin4030 salihrkc's solution gives probabilities .33, .33, and .34, i.e., not quite uniformly distributed. Having said that, if you want unequal probabilities then that answer is one way to do it. For instance, change the tests to .25 and .25 if you want to get 100 twice as often as the other two outcomes. – pjs Dec 14 '13 at 17:05
  • Doh! Make that .25 and .5 if you want to get 100 twice as often and do it correctly. ;) – pjs Dec 15 '13 at 19:12
1

Random is your solution for it:

public static int generateRandomNumber(int[] availableCollection) {
   Random rand = new Random();
   return availableCollection[rand.nextInt(availableCollection.length)];
}
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0
 {1,3,100} 

Store them in an array and then select a random element from there. To select random element, see this: http://answers.yahoo.com/question/index?qid=20081025124826AAR8rmY

Eisa Adil
  • 1,743
  • 11
  • 16
0

Java Math.random() generates random numbers between 0.0 and 1.0 you can write a code for what you want. For example:

double random = new Math.random();
random = myRandom(random);

    public double myRandom(double random){

        if(random < 0.33){return 1;}
        else if(random < 0.66) {return 3;}
        else {return 100;}
    }
Salih Erikci
  • 5,076
  • 12
  • 39
  • 69