discrete distribution

I'm familiar with discrete and weighted distributions,I just
can't seem to figure out how to do what I need...
I need to be able to pick a random item from a vector with eqch
item having a different probability of being chosen. Also, I'm looking to manually fill the vector with specific items. I can't seem to figure
this out or find the appropriate code
Any help is welcome

Last edited on
Not sure which part you're having problem with but here is an example using std::discrete_distribution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <random>

int main()
{
	std::vector<std::string> items =    {"screwdriver", "door", "house", "pizza"};
	std::vector<double> probabilities = { 10,            20,     50,      20};
	
	std::mt19937 rng(std::random_device{}());
	std::discrete_distribution<> dist(probabilities.begin(), probabilities.end());
	
	int random_item_index = dist(rng);
	const std::string& random_item = items[random_item_index];
	std::cout << "Random item: " << random_item << "\n";
}
That looks like it may do what I need...thank you. I'll try it tonight and report back.
Is there a way to set it up to run more than once and to eliminate previous choices as possible future choices?
A 'while' loop, and remove the eliminated element from the vector and re-initialize the dist every time in the loop.
You shouldn't need to re-initialize the rng each loop iteration. That can happen once, at the beginning before the loop.
Last edited on
Perfect. Thank you.
Okay...the code Peter87 shared works, but it always chooses the last item in the vector no matter how the probability is distributed. Any ideas?
What is your compiler? What is your standard library? Exact version numbers please.

Some obsolete implementations don't completely implement the stuff in <random>. For example std::random_device might be pseudorandom (if I remember correctly) in some versions of libstdc++.
Last edited on
Yeah, std::random_device was broken in some old versions of MinGW.

You might want to use the current time as seed instead.
 
std::mt19937 rng(std::time(nullptr));
Last edited on
Topic archived. No new replies allowed.