Random Integer: Android
I'm guessing this is very simple, but for som开发者_StackOverflow中文版e 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.
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;
use following function:
int fun(int a, int b) {
Random r = new Random();
if(r.nextInt(2)) return a;
else return b;
}
This will return a or b with uniform distribution. That means in a very simple way: If you run this function N times, expected occurrence of 'a' and 'b' are N/2 each.
精彩评论