3

So lets say I want to randomly choose from the set of two numbers 1 and 3.

How do I go about doing that? Do I just assign int a to 1, int b to 3, and then do randomly select from a and b?

DimaSan
  • 12,264
  • 11
  • 65
  • 75
  • 4
    This is relevant: http://stackoverflow.com/questions/9055287/select-a-random-value-from-an-array#9055314 – Eli Sadoff Oct 28 '16 at 18:49
  • 2
    Or that http://stackoverflow.com/questions/8878015/return-true-or-false-randomly – Tunaki Oct 28 '16 at 18:51
  • 1
    Possible duplicate of [Generating random integers in a specific range](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range) – Alessandro Da Rugna Oct 29 '16 at 10:53

2 Answers2

5

If there are only two numbers to choose from then you can use the value of a boolean, because it returns either true or false.

One-liner solution assuming that int a = 1 and int b = 3:

int randomOfTwoInts = new Random().nextBoolean() ? a : b;
DimaSan
  • 12,264
  • 11
  • 65
  • 75
1

If you have a specific list of numbers then put them in list structure (an array works well). Then you have the easier task of looking for a random index in the range from 0 to last array index. This post lists strategies for doing that:How do I generate random integers within a specific range in Java?

Community
  • 1
  • 1
bknights
  • 14,408
  • 2
  • 18
  • 31