Nim Generate Random Numbers with Examples?

This tutorial explains Nim Random Generators

Nim Random Number Generator Example

random is a nim module that provides a procedure to generate Random numbers. It is based on the xoroshiro128 library.

  • Import random library into a code
  • Next, call randomize() method to initialize a random generator. This is required to generate a random number for every call
  • Rand(n) procedure returns the random number between 1 to n.

Here is an example

import std/random

randomize()

let num = rand(100)
echo num

Generates a new random number for every call. Output:

12

Nim Random element Generator from an array example

Sometimes, you have an array of elements, you want to pick an element randomly from an array.

random module has a sample procedure that returns a random element from an array.

Here is an example

import std/random

randomize()
let numbers = ["one", "two", "three", "four", "five"]
let randomElement = sample(numbers)
echo randomElement
three

Nim random generator using

mersenne module is one of the nim modules to provide a procedure to generate random numbers newMersenneTwister object created with uint32.high call getNum on a given Random number.

Here is an example

import std/mersenne
var randomNumbers = newMersenneTwister(uint32.high)
echo randomNumbers.getNum()