Random Numbers in Dart

Here’s the translation of the Go code for random numbers into Dart, along with explanations in Markdown format suitable for Hugo:

Dart’s dart:math library provides pseudorandom number generation.

import 'dart:math';

void main() {
  // Create a random number generator
  final random = Random();

  // For example, nextInt(100) returns a random int n,
  // 0 <= n < 100.
  print('${random.nextInt(100)},${random.nextInt(100)}');

  // nextDouble() returns a double d,
  // 0.0 <= d < 1.0.
  print(random.nextDouble());

  // This can be used to generate random doubles in
  // other ranges, for example 5.0 <= d' < 10.0.
  print('${5 + random.nextDouble() * 5},${5 + random.nextDouble() * 5}');

  // If you want a known seed, create a new
  // Random object with a specific seed.
  final seededRandom = Random(42);
  print('${seededRandom.nextInt(100)},${seededRandom.nextInt(100)}');

  // Creating another Random object with the same seed
  // will produce the same sequence of random numbers.
  final seededRandom2 = Random(42);
  print('${seededRandom2.nextInt(100)},${seededRandom2.nextInt(100)}');
}

To run the program, save it as random_numbers.dart and use dart run:

$ dart run random_numbers.dart
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

Some of the generated numbers may be different when you run the sample.

See the dart:math library docs for references on other random quantities that Dart can provide.

Note that Dart’s random number generation is simpler than Go’s, as it doesn’t have separate source and generator types. Instead, you create a Random object which serves as both the source and generator. The Random constructor can optionally take a seed value.

Also, Dart doesn’t have a built-in PCG (Permuted Congruential Generator). It uses a different algorithm for its pseudo-random number generation. If you need a specific type of random number generator, you might need to implement it yourself or use a third-party package.