In my algorithm, I have two values โโthat I need to randomly select, but each of them must be selected a predetermined number of times.
So far, my solution has been to put the selection in the vector the correct number of times, and then shuffle it. In C ++:
// Example choices (can be any positive int) int choice1 = 3; int choice2 = 4; int number_of_choice1s = 5; int number_of_choice2s = 1; std::vector<int> choices; for(int i = 0; i < number_of_choice1s; ++i) choices.push_back(choice1); for(int i = 0; i < number_of_choice2s; ++i) choices.push_back(choice2); std::random_shuffle(choices.begin(), choices.end());
Then I save the iterator to choices , and whenever I need a new one, I increment the iterator and grab it.
This works, but it seems that there may be a more efficient way. Since I always know how many of each value I will use, I wonder if there is a more algorithmic way to do this, and not just store the values.
Sean lynch
source share