Skip to content

Instantly share code, notes, and snippets.

@divmgl
Last active January 7, 2017 05:05
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 divmgl/a1509fb85870a8824e5390d6024b5a88 to your computer and use it in GitHub Desktop.
Save divmgl/a1509fb85870a8824e5390d6024b5a88 to your computer and use it in GitHub Desktop.
Weighted random function
#include <iostream>
#include <array>
#include <map>
#include <random>
using std::cout;
using std::endl;
using std::string;
using std::array;
class item
{
public:
string name;
int weight;
};
struct descending
{
template <class item>
bool operator()(item const &a, item const &b) const
{
return b.weight < a.weight;
}
};
template<std::size_t SIZE>
item randomize(array<item, SIZE> items)
{
int sum = 0;
std::map<string, double> weights;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);
double seed = dis(gen);
for (item current : items)
{
sum += current.weight;
}
for (item current : items)
{
weights[current.name] = (double)current.weight / sum;
}
std::sort(items.begin(), items.end(), descending());
for (item current : items)
{
if (seed < weights[current.name]) return current;
}
return items[items.size() - 1];
}
int main()
{
array<item, 2> players =
{{
{ "michael", 10 },
{ "james", 100 }
}};
item player = randomize(players);
cout << player.name << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment