Last active
January 7, 2017 05:05
-
-
Save divmgl/a1509fb85870a8824e5390d6024b5a88 to your computer and use it in GitHub Desktop.
Weighted random function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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