0Pricing
C++ Academy · Lesson

Practical Examples

Dice, shuffles, and sampling.

Rolling Dice

A six-sided die is a uniform_int_distribution(1, 6) fed by a seeded engine.

#include <iostream>
#include <random>

int main() {
    std::mt19937 gen(2026);
    std::uniform_int_distribution<int> die(1, 6);
    for (int i = 0; i < 5; ++i) std::cout << die(gen) << ' ';
    std::cout << '\n';
    return 0;
}

Summing Two Dice

Rolling two dice and summing them produces the familiar 2 to 12 range with a peak at 7.

#include <iostream>
#include <random>

int main() {
    std::mt19937 gen(1);
    std::uniform_int_distribution<int> die(1, 6);
    int total = die(gen) + die(gen);
    std::cout << "two dice sum: " << total << '\n';
    return 0;
}

All lessons in this course

  1. Random Engines
  2. Distributions
  3. Seeding Properly
  4. Practical Examples
← Back to C++ Academy