discrete distribution

Dec 7, 2022 at 7:58pm
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 Dec 7, 2022 at 8:09pm
Dec 7, 2022 at 8:33pm
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";
}
Dec 7, 2022 at 8:43pm
That looks like it may do what I need...thank you. I'll try it tonight and report back.
Dec 7, 2022 at 9:03pm
Is there a way to set it up to run more than once and to eliminate previous choices as possible future choices?
Dec 7, 2022 at 9:16pm
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 Dec 7, 2022 at 9:17pm
Dec 7, 2022 at 9:25pm
Perfect. Thank you.
Dec 8, 2022 at 1:11am
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?
Dec 8, 2022 at 3:47am
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 Dec 8, 2022 at 3:48am
Dec 8, 2022 at 5:57am
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 Dec 8, 2022 at 5:58am
Topic archived. No new replies allowed.