Java 从两个数字中随机选择一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22447246/
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
Pick a number randomly from two numbers
提问by Basant Singh
I have two integers, let them be
我有两个整数,让它们成为
int a = 35:
int b = 70;
I want to pick one of them randomly at runtime and assign to another variable. I.e.
我想在运行时随机选择其中一个并分配给另一个变量。IE
int c = a or b:
One of the ways that come into my mind is to create an array with these two integers and find a random integer between 0 and 1 and use it as the index of the array to get the number..
我想到的方法之一是用这两个整数创建一个数组,并在 0 和 1 之间找到一个随机整数,并将其用作数组的索引以获取数字。
Or randomize boolean and use it in if-else.
或者随机化布尔值并在 if-else 中使用它。
My question is that is there a better and more efficient way to achieve this? I.e. pick a number from two previously defined integers?
我的问题是有没有更好、更有效的方法来实现这一目标?即从两个先前定义的整数中选择一个数字?
采纳答案by Andreas Troelsen
Is there a specific reason you are asking for a more efficient solution? Unless this functionality sits in a very tight inner loop somewhere (e.g. in a ray tracer), you might be trying to prematurely optimizeyour code.
您是否有特定原因要求更有效的解决方案?除非此功能位于某处非常紧密的内部循环中(例如在光线跟踪器中),否则您可能会尝试过早地优化您的代码。
If you would like to avoid the array, and if you don't like the "bloat" of an if-statement, you can use the ternary choice operator to pick between the two:
如果您想避免使用数组,并且不喜欢 if 语句的“膨胀”,则可以使用三元选择运算符在两者之间进行选择:
int a = 35;
int b = 70;
int c = random.nextBoolean() ? a : b;
where random
is an instance of java.util.Random
. You can store this instance as a final static
field in your class to reuse it.
random
的实例在哪里java.util.Random
。您可以将此实例存储为final static
类中的字段以重用它。
If you don't require true randomness, but just want to switch between the two numbers in each invocation of the given block of code, you can get away with just storing a boolean
and toggling it:
如果您不需要真正的随机性,而只想在给定代码块的每次调用中在两个数字之间切换,您只需存储 aboolean
并切换它即可:
...
int c = toggle ? a : b;
toggle = !toggle;
Since I can't comment on other answers, I'd like to point out an issue with some of the other answers that suggest generating a random integer in a bigger range and making a decision based on whether the result is odd or even, or if it's lower or greater than the middle value. This is in effect the exact same thing as generating a random integer between 0 and 1, except overly complicated. The nextInt(n)
method uses the modulo operatoron a randomly generated integer between -2^31 and (2^31)-1, which is essentially what you will be doing in the end anyway, just with n = 2
.
由于我无法对其他答案发表评论,我想指出一些其他答案的问题,这些答案建议在更大范围内生成一个随机整数并根据结果是奇数还是偶数做出决定,或者如果它低于或高于中间值。这实际上与生成 0 到 1 之间的随机整数完全相同,只是过于复杂。该nextInt(n)
方法在 -2^31 和 (2^31)-1 之间随机生成的整数上使用模运算符,这基本上就是您最终要做的事情,只是使用n = 2
.
If you are using the standard library methods like Collections.shuffle()
, you will again be overcomplicating things, because the standard library uses the random number generator of the standard library.
如果您使用标准库方法,例如Collections.shuffle()
,您将再次使事情变得过于复杂,因为标准库使用标准库的随机数生成器。
Note that all of the suggestions (so far) are lessefficient than my simple nextBoolean()
suggestion, because they require unnecessary method calls and arithmetic.
请注意,所有的建议(到目前为止)是少比我的简单而有效nextBoolean()
的建议,因为它们需要不必要的方法调用和算术。
回答by akshay2000
In my opinion, main problem here is entropy for two numbers rather than making use of that entropy. Indexed array or boolean are essentially the same thing. What else you can do (and, hopefully, it will be more random) is to make Java give you a random number between limits say 0 to 100. Now, if the chosen random number is odd, you pick int c = a
. Pick b
otherwise. I could be wrong, but picking random between 0 to 100 seems more random as compared to picking random between two numbers.
在我看来,这里的主要问题是两个数字的熵,而不是利用该熵。索引数组或布尔值本质上是一回事。你还能做什么(希望它会更随机)是让 Java 给你一个介于 0 到 100 之间的随机数。现在,如果选择的随机数是奇数,你选择int c = a
. 选择b
其他。我可能是错的,但与在两个数字之间随机选择相比,在 0 到 100 之间随机选择似乎更随机。
回答by Baby
Another way to do this is, store the numbers into a list, shuffle, and take the first element.
另一种方法是,将数字存储到列表中,随机排列,然后取出第一个元素。
ArrayList<Integer> numbers=new ArrayList<Integer>();
numbers.add(35);
numbers.add(70);
Collections.shuffle(numbers);
numbers.get(0);
回答by kiDDevil
Randomize an integer between 1 and 10, if it's more than 5 then take the value of b other wise go with a. As far as I know there are no other ways to select from integers.
随机化 1 到 10 之间的整数,如果它大于 5,则取 b 的值,否则使用 a。据我所知,没有其他方法可以从整数中进行选择。
回答by Nithin CV
You can simply use secure random generator(java.security.SecureRandom
).
您可以简单地使用安全随机生成器( java.security.SecureRandom
)。
try {
r = SecureRandom.getInstance("SHA1PRNG");
boolean b1 = r.nextBoolean();
if (b1) {
c = a;
} else {
c = b;
}
} catch (NoSuchAlgorithmException nsae) {
// Process the exception in some way or the other
}
Refer this link for more information
请参阅此链接以获取更多信息
回答by Rocky
int a=1;
int b=2;
int get = new Random().nextBoolean()? a : b;