nextInt method

  1. @nonVirtual
  2. @override
int nextInt(
  1. int max
)
override

Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive.

Implementation note: The default implementation supports max values between 1 and (1<<32) inclusive.

Example:

var intValue = Random().nextInt(10); // Value is >= 0 and < 10.
intValue = Random().nextInt(100) + 50; // Value is >= 50 and < 150.

Implementation

@nonVirtual
@override
int nextInt(int max) {
  if (max < 0 || max > _bit32) {
    throw ArgumentError.value(max, 'max');
  }
  var attempts = 0;
  while (true) {
    final x = nextUint32();

    // To avoid modulo bias, we only accept values
    // that are within a multiple of [max].
    final nonAcceptedRange = _bit32 % max;
    if (x < _bit32 - nonAcceptedRange) {
      // Accept the value.
      return x % max;
    }
    if (attempts == 128) {
      // Give up and accept the value anyway.
      // This should never happen.
      assert(false);
      return x % max;
    }
    attempts++;
  }
}