I use the C++ random number utility library in quite a few places. It might not be perfectly comfortable (e.g. no base class for an arbitrary distribution), but - I've learned to live with it.
Now I happen to need to uniformly sample values from an enumerated type. I know, there's a question on that on SO already:
however, that one:
Assumes all enum values are contiguous, i.e. it won't work for
enum Color { Red = 1, Green = 2, Blue = 4 }
where we want each of these three values to be sampled with probability 1/3.
- Does not provide the functionality of
std::uniform_distribution<>
, i.e. it doesn't work with a random engine you pass it and so on.
Obviously I can't use std::uniform_int_distribution<Color>
, if only for reason 1 above. What should I do instead?
Notes:
- The code must be generic, i.e. the enum type would be a template parameter.
- Since it is likely I would need some instrumentation over just the rough enum, you may assume I have it; just state your assumption explicitly.
- Specifically, and if it helps, suppose I use Better Enums, making me fully decked out with all the bells and whistles.
- If there's somehow an idiomatic way of doing this not involving any such instrumentation, that would make for a great answer, but I doubt it.
- C++11/14-only solutions are acceptable.
- Multiple enum identifiers with the same value do not get double the frequency, they're just aliases of each other. If you have a simple solution assuming these do not exist, that would also be relevant, though suboptimal.