Skip to content

Instantly share code, notes, and snippets.

@muupan
Created December 22, 2014 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muupan/a6570982ba10241b3fb8 to your computer and use it in GitHub Desktop.
Save muupan/a6570982ba10241b3fb8 to your computer and use it in GitHub Desktop.
roulette wheel selection using std::discrete_distribution
#include <array>
#include <iostream>
#include <random>
int main() {
constexpr std::array<double, 3> fitness_values = {1, 1.5, 2};
// Constructor is O(n)
std::discrete_distribution<std::size_t> dist(fitness_values.begin(), fitness_values.end());
std::array<size_t, 3> table;
table.fill(0);
std::mt19937 random_engine;
for (auto i = 0; i < 100000; ++i) {
// Sampling is O(1)
++table[dist(random_engine)];
}
for (auto i = 0; i < 3; ++i) {
std::cout << i << " was selected " << table[i] << " times." << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment