java 随机整数:Android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3993141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random Integer: Android
提问by Hyman Love
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.
我猜这很简单,但由于某种原因我无法弄清楚。那么,你如何从两个数字中选择一个随机整数。我想从 1 和 2 中随机选择一个整数。
回答by Mark Elliot
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:
就用标准的均匀随机分布,采样,如果小于0.5就选一个,如果大于就选另一个:
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):
或者,您可以使用以下nextInt
方法,该方法将大小的上限(范围内不包括)作为输入,然后偏移以说明它返回 0(包含的最小值):
int randInt = new Random().nextInt(2) + 1;
回答by Vedsar Kushwaha
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.
这将返回具有均匀分布的 a 或 b。这意味着以一种非常简单的方式:如果您运行此函数 N 次,“a”和“b”的预期出现次数分别为 N/2。