mercredi 21 décembre 2016

The best(fastest) way to choose random element from set of variables respecting their chances in C++

I have two arrays, where one stores objects, and another one stores their chances. I want to choose random one of those, respecing their chances. This code must run as fast as possible.

The arrays:

int size = 4;

std::string* nameArray;
nameArray = new std::string[size];

nameArray[0] = "A";
nameArray[1] = "B";
nameArray[2] = "C";
nameArray[3] = "D";


int* chances;
chances = new int[size];

chances[0] = 30;
chances[1] = 30;
chances[2] = 10;
chances[3] = 30;

And now I want to pick one string where

'A' has 30%

'B' has 30%

'C' has 10%

'D' has 30%


I was thinking about changing the chances array into this:

chances[0] = 30;
chances[1] = 60;
chances[2] = 70;
chances[3] = 100;

Then draw a random number between 0 and 100, and then pick up element if its in specific range. For example if I draw 81, then I take the last element because its greater than 70 and lower than 100.




Aucun commentaire:

Enregistrer un commentaire