THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial explains Nim Random Generators
random
is a nim module that provides a procedure to generate Random numbers. It is based on the xoroshiro128 library.
Here is an example
import std/random
randomize()
let num = rand(100)
echo num
Generates a new random number for every call. Output:
12
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
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()
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts