PDA

View Full Version : Possible to get random value in QMultiHash/Map?



weevil
29th June 2010, 11:41
I have a QMultiHash storing a crossword dictionary with int word length keys and qstring word values. I want to be able to get a random word for a given length, instead of the first value associated with the key, both for randomization and also for use in my word placing algorithm that tries different words for a given length. I could remove a used word value from the hash to solve the latter problem, but that's not ideal and still leaves the program attempting to use the same word to start each time.

Is there a way to do this or a better alternative? I'd like to still be able to use QHash as I have a ton of entries and need quick lookup.

tbscope
29th June 2010, 11:49
There's always a way.

Here's what I would do:
You can get all the items from a multihash that have the same key (word length)
Get the item count of that list.
Generate a random number in the range of the item count.
Then use that random number to get one item out of the list with the same key.

weevil
29th June 2010, 12:00
Nice solution, I should've seen it but it's late and my brain hurts!

Would be nice if there were a built-in randomValue( const Key &key ) type function for these situations, since it seems like such a common need and handling it your way puts an unwanted performance hit on using a hash in the first place. Thanks for the tip!