Nim Programming Cookbook // Random

Random Stuff

Problem: Generate Random Number

Generate a random number less than x.


import random

# Print 19 random numbers from 0 to 119
for i in 1..<20:

Problem: Sample 10 random lines from a file

How to sample n lines from a large text file?


var fruits = newSeq[string]()

# Iterate over all lines in "fruits.txt"
for line in "fruits.txt".lines:

# Randomize the seed (current time is used to randomize it by default)

# Select 10 random fruits
for i in 0..<10:
  echo i, ", ", random(fruits)