Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Integer: Android

Tags:

java

android

I'm guessing this is very simple, but for some reason I am unable to figure it out. So, how do you pick a random integer out of two numbers. I want to randomly pick an integer out of 1 and 2.

like image 261
Jack Love Avatar asked Dec 28 '22 06:12

Jack Love


1 Answers

Just use the standard uniform random distribution, sample it, if it's less than 0.5 choose one value, if it's greater, choose the other:

 int randInt = new Random().nextDouble() < 0.5 ? 1 : 2;

Alternatively, you can use the nextInt method which takes as input a cap (exclusive in the range) on the size and then offset to account for it returning 0 (the inclusive minimum):

int randInt = new Random().nextInt(2) + 1;
like image 165
Mark Elliot Avatar answered Jan 06 '23 20:01

Mark Elliot