Random algorithm with priority to one end
I am writing a little program with a GUI in C++ and Qt. It is supposed to be similar to a vocabulary trainer. I will use it for my own studying.
I have a QList of objects (name and description as string for example).
Then I have a second QList with ints in it. For every object in my other list, an int is in this list. Start value is 50 for every object; if user clicks correct, it gets decremented, vice versa. So a object with value 70 should be shown more often to the user than an object with value 30. So in the correct answer method I increase/decrease it, sort the QList and use my random algorithm:
if(packList.count()==0) // the QList with objects
return;
int Min = 0;
int Max = packList.count()-1; // -1 because i need the index
qsrand(QTime::currentTime().msec());
if (Min > Max)
{
int Temp = Min;
Min = Max;
开发者_Python百科Max = Temp;
}
int randNum = ((rand()%(Max-Min+1))+Min);
setPage(randNum); // randNum will be used as index in this method
Now what I need is a way to implement my priority in this random algorithm. I don't want the ones with a higher value to appear 90% of the time, but just more often, just like a vocabulary trainer.
First a remark: You should use qsrand only once at the beginning of the program.
Now to your algorithm: First get the sum of all your values, let us call it sumValues, then compute your random number between 0 and sumValues-1. Go through your list and sum the values into the variable currentSum until it is greater or equal to your random number, and use the index of this entry. This will be more efficient if you sort your list by decreasing values.
精彩评论