nextBetween method

int nextBetween(
  1. int low,
  2. int high
)

Generates a random integer between low and high, both inclusive. The bounds may be given in either order.

The range may span at most 2^32 values (high - low <= 0xFFFFFFFF). It takes two 32-bit draws, combined into a 53-bit value (exact on every platform), modulo the range size. The modulo bias is below size / 2^53: under 1 in 2 million even for the widest range.

Throws:

Implementation

int nextBetween(int low, int high) {
  if (low == high) {
    return low;
  }
  int t, range;
  if (low > high) {
    t = low;
    low = high;
    high = t;
  }
  range = high - low; // negative if it overflows
  if (range < 0 || range > _mask32) {
    throw ArgumentError('The range must span at most 2^32 values');
  }
  t = (nextInt() & 0x1FFFFF) * _pow32 + nextInt();
  return low + t % (range + 1);
}