简体   繁体   English

选择大于Integer.MAX_VALUE的范围内的随机整数?

[英]Choose random integer in a range bigger than Integer.MAX_VALUE?

I know there are another questions about random in a range but none of their answers accomplishes what I am trying to do. 我知道在一个范围内还有另外一个关于随机的问题,但他们的答案都没有完成我想要做的事情。 Actually they have the same error I have. 实际上他们有同样的错误。 I wrote this simple function to generate random with range. 我写了这个简单的函数来生成随机范围。

Random m_random = new Random();
...
public int RandomWithRange(int min, int max) {
    return m_random.nextInt(max - min + 1) + min;
}

If range is bigger than Integer.MAX_VALUE, it throws an IllegalArgumentException: n must be positive. 如果range大于Integer.MAX_VALUE,则抛出IllegalArgumentException:n必须为正数。 I know it overflows and turn to a negative number. 我知道它溢出并转向负数。 My question is how to handle that? 我的问题是如何处理?

Example ranges; 示例范围;

  • [0, Integer.MAX_VALUE] [0,Integer.MAX_VALUE]
  • [Integer.MIN_VALUE, Integer.MAX_VALUE] [Integer.MIN_VALUE,Integer.MAX_VALUE]
  • [-100, Integer.MAX_VALUE] [-100,Integer.MAX_VALUE]

Note: min and max must be inclusive. 注意:min和max必须包含在内。

You cannot use int in this case. 在这种情况下,您不能使用int。 You need to go with BigInteger . 你需要使用BigInteger The following constructor does what you want (need some tweaking for your needs of course): 以下构造函数执行您想要的操作(当然需要根据您的需要进行调整):

BigInteger(int numBits, Random rnd) 

Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2numBits - 1), inclusive. 构造一个随机生成的BigInteger,均匀分布在0到(2numBits - 1)的范围内,包括0和(2numBits - 1)。

The problem you have is that (max - min) overflows and gives you a negative value. 你遇到的问题是(max - min)溢出并给你一个负值。

You can use a long instead. 你可以使用long而不是。

public int randomWithRange(int min, int max) {
    return (int) ((m_random.nextLong() & Long.MAX_VALUE) % (1L + max - min)) + min;
}

你有没有考虑过随机加倍然后再回到int

return (int)(m_random.nextDouble() * ((double)max - (double)min) + min);

The most "dumb but definitely correct" solution I can think of: 我能想到的最“愚蠢但绝对正确”的解决方案:

if (max - min + 1 > 0) // no overflow
  return delta + random.nextInt(max - min + 1);
else {
  int result;
  do {
    result = random.nextInt();
  } while (result < min || result > max);
  // finishes in <= 2 iterations on average
  return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM