Weighted Random Tables
Most random choices in games are not fair dice. A chest should drop common items often and legendary ones rarely; an enemy spawner should favor grunts over elites; a dialogue system should pick a fresh line more often than the one it just said. These are weighted random tables.
Cumulative weights
Give every entry a weight. Draw a number r in [0, totalWeight) and walk the list, subtracting weights until r falls inside an entry. With precomputed cumulative sums you can binary-search instead of walking, which matters for big tables.
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <string>
#include <vector>
#include <algorithm>
struct Pcg32 {
uint64_t state, inc;
Pcg32(uint64_t seed, uint64_t stream = 54) : state(0), inc((stream << 1) | 1) { next(); state += seed; next(); }
uint32_t next() {
uint64_t old = state;
state = old * 6364136223846793005ULL + inc;
uint32_t x = uint32_t(((old >> 18) ^ old) >> 27), rot = uint32_t(old >> 59);
return (x >> rot) | (x << ((-rot) & 31));
}
double nextDouble() { return next() / 4294967296.0; }
};
struct LootTable {
std::vector<std::string> names;
std::vector<double> cumulative;
void add(const std::string& name, double weight) {
names.push_back(name);
cumulative.push_back((cumulative.empty() ? 0 : cumulative.back()) + weight);
}
const std::string& roll(Pcg32& rng) const {
double r = rng.nextDouble() * cumulative.back();
auto it = std::upper_bound(cumulative.begin(), cumulative.end(), r); // first sum > r
return names[it - cumulative.begin()];
}
};
int main() {
LootTable chest;
chest.add("coins", 60);
chest.add("potion", 25);
chest.add("sword", 12);
chest.add("dragon egg", 3);
Pcg32 rng(2025);
std::vector<int> counts(chest.names.size(), 0);
const int N = 10000;
for (int i = 0; i < N; i++) {
const std::string& item = chest.roll(rng);
counts[std::find(chest.names.begin(), chest.names.end(), item) - chest.names.begin()]++;
}
std::cout << std::fixed << std::setprecision(1);
for (size_t i = 0; i < counts.size(); i++)
std::cout << std::setw(11) << chest.names[i] << ": " << std::setw(5) << counts[i] << " ("
<< 100.0 * counts[i] / N << "%)\n";
} coins: 5964 (59.6%)
potion: 2548 (25.5%)
sword: 1191 (11.9%)
dragon egg: 297 (3.0%)
Over 10,000 rolls the frequencies land close to the weights (60/25/12/3 percent), but not exactly: that is what randomness looks like. Weights don't have to add up to 100; they are relative, so adding a new item doesn't require re-balancing the others.
Streaks feel unfair: bad luck protection
True randomness produces streaks. With a 3% drop rate, about 1 player in 20 will open 100 chests without getting a dragon egg, and those players complain loudly. Games use pity timers: each failure raises the chance a little, and a success resets it.
#include <iostream>
#include <cstdint>
struct Pcg32 {
uint64_t state, inc;
Pcg32(uint64_t seed, uint64_t stream = 54) : state(0), inc((stream << 1) | 1) { next(); state += seed; next(); }
uint32_t next() {
uint64_t old = state;
state = old * 6364136223846793005ULL + inc;
uint32_t x = uint32_t(((old >> 18) ^ old) >> 27), rot = uint32_t(old >> 59);
return (x >> rot) | (x << ((-rot) & 31));
}
double nextDouble() { return next() / 4294967296.0; }
};
int longestDrought(bool pity, uint64_t seed) {
Pcg32 rng(seed);
const double base = 0.03;
double chance = base;
int drought = 0, worst = 0;
for (int chest = 0; chest < 20000; chest++) {
if (rng.nextDouble() < chance) { drought = 0; chance = base; }
else {
drought++;
if (drought > worst) worst = drought;
if (pity) chance += 0.005; // +0.5% per miss
}
}
return worst;
}
int main() {
std::cout << "longest streak without an egg (20000 chests):\n";
std::cout << " pure 3% chance: " << longestDrought(false, 99) << " chests\n";
std::cout << " with pity timer: " << longestDrought(true, 99) << " chests\n";
}longest streak without an egg (20000 chests):
pure 3% chance: 189 chests
with pity timer: 49 chests
Shuffle bags
For things that should feel evenly spread (Tetris pieces, which footstep sound plays, which enemy speaks), put every option in a "bag", shuffle it, and deal from it until it's empty, then refill. Every option appears exactly once per round, so long gaps and repeats are impossible. Modern Tetris guidelines call this the "7-bag".
#include <iostream>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
struct Pcg32 {
uint64_t state, inc;
Pcg32(uint64_t seed, uint64_t stream = 54) : state(0), inc((stream << 1) | 1) { next(); state += seed; next(); }
uint32_t next() {
uint64_t old = state;
state = old * 6364136223846793005ULL + inc;
uint32_t x = uint32_t(((old >> 18) ^ old) >> 27), rot = uint32_t(old >> 59);
return (x >> rot) | (x << ((-rot) & 31));
}
uint32_t below(uint32_t n) { return uint32_t((uint64_t(next()) * n) >> 32); } // [0, n)
};
struct ShuffleBag {
std::vector<char> items, bag;
Pcg32 rng;
ShuffleBag(std::vector<char> it, uint64_t seed) : items(std::move(it)), rng(seed) {}
char draw() {
if (bag.empty()) {
bag = items;
for (size_t i = bag.size() - 1; i > 0; i--) // Fisher-Yates shuffle
std::swap(bag[i], bag[rng.below(uint32_t(i + 1))]);
}
char c = bag.back();
bag.pop_back();
return c;
}
};
int main() {
ShuffleBag pieces({'I', 'O', 'T', 'S', 'Z', 'J', 'L'}, 31);
for (int round = 0; round < 3; round++) {
std::string s;
for (int i = 0; i < 7; i++) s += pieces.draw();
std::cout << "bag " << round + 1 << ": " << s << "\n";
}
}bag 1: IOZSJTL
bag 2: SZLOITJ
bag 3: LOITJZS
Each line contains all seven pieces exactly once. Notice the Fisher-Yates shuffle draws below(i + 1): a common bug is drawing from the whole range every time, which produces a biased shuffle.
Tip: Show players honest odds (many regions require it for loot boxes), and test your tables with thousands of simulated rolls like the first example, not by opening chests by hand.
Test yourself
Weights are coins 6, potion 3, gem 1. What is the chance of a gem?
- 1%
- 10%
- 33%
- 1/6
What does a pity timer do?
- Lowers the chance after each success
- Raises the chance after each failure until a success resets it
- Makes every roll identical
- Removes rare items
What does a shuffle bag guarantee?
- Every item appears exactly once per bag
- Rare items appear first
- The same order every time
- Higher weights for common items