Learn C++
#include "advanced/random.hpp"

Random Numbers with <random> in C++

//concept

The <random> library separates generation into engines (the raw source, e.g. std::mt19937 seeded once) and distributions (shaping: uniform_int_distribution, normal_distribution, shuffle). This beats rand()%N on every axis — statistical quality, range correctness (no modulo bias), and reproducibility via explicit seeds.

Seed once per program (std::random_device, or a fixed seed for deterministic tests), then draw repeatedly. Threading? Engines aren't thread-safe — give each thread its own. For shuffling, std::shuffle with your engine replaces hand-rolled swaps.

//how it works
1

Engine plus distribution

std::mt19937 rng(seed); produces raw bits; std::uniform_int_distribution<int> d(1, 6); shapes them into dice rolls.

2

Seed deliberately

std::random_device for real randomness, fixed constants for reproducible tests — never re-seed per draw.

3

No modulo bias

rand() % n skews toward low values; distributions map ranges uniformly by construction.

4

Shuffle properly

std::shuffle(v.begin(), v.end(), rng); permutes uniformly — the correct Fisher-Yates, not a sorting hack.

//example
#include <iostream>
#include <random>
 
int main() {
std::mt19937 rng(42);
std::uniform_int_distribution<int> dice(1, 6);
std::cout << dice(rng) << ", " << dice(rng) << std::endl;
return 0;
}
Output
3, 5
1The Mersenne Twister engine seeds deterministically with 42 — same seed replays the same sequence.
2Each dice(rng) call shapes engine output into a uniform 1–6 roll.
33, 5 prints — fixed seed means this exact output reproduces on every run, ideal for tests.
//use cases
Dice, decks, and loot tables with uniform distributions
Reproducible simulations via fixed seeds
Normal/exponential sampling for modeling and Monte Carlo
Per-thread engines in multithreaded samplers

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.