Shervin4030
Shervin4030

Reputation: 27

Generate random number from the set {1, 3, 100}

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).

Upvotes: 1

Views: 5462

Answers (4)

Salih Erikci
Salih Erikci

Reputation: 5087

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;}
    }

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

Random is your solution for it:

public static int generateRandomNumber(int[] availableCollection) {
   Random rand = new Random();
   return availableCollection[rand.nextInt(availableCollection.length)];
}

Upvotes: 1

Eisa Adil
Eisa Adil

Reputation: 1733

 {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

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168825

  • 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.

Upvotes: 6

Related Questions