Results 1 to 3 of 3

Thread: Possible to get random value in QMultiHash/Map?

  1. #1
    Join Date
    Jun 2010
    Posts
    12
    Thanks
    1
    Qt products
    Qt4
    Platforms
    MacOS X Unix/X11 Windows

    Default Possible to get random value in QMultiHash/Map?

    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.

  2. #2
    Join Date
    Jan 2006
    Location
    Belgium
    Posts
    1,938
    Thanked 268 Times in 268 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows
    Wiki edits
    20

    Default Re: Possible to get random value in QMultiHash/Map?

    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.

  3. The following user says thank you to tbscope for this useful post:

    weevil (29th June 2010)

  4. #3
    Join Date
    Jun 2010
    Posts
    12
    Thanks
    1
    Qt products
    Qt4
    Platforms
    MacOS X Unix/X11 Windows

    Default Re: Possible to get random value in QMultiHash/Map?

    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!

Similar Threads

  1. Replies: 1
    Last Post: 7th April 2010, 16:26
  2. QDataStream << QMultiHash upper bounds?
    By ucntcme in forum Qt Programming
    Replies: 2
    Last Post: 25th June 2009, 22:40
  3. random
    By raphaelf in forum General Programming
    Replies: 9
    Last Post: 6th June 2007, 12:33
  4. QMultiHash
    By steg90 in forum Qt Programming
    Replies: 5
    Last Post: 24th May 2007, 12:42
  5. QMultiHash - crashing
    By steg90 in forum Qt Programming
    Replies: 16
    Last Post: 23rd May 2007, 13:18

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.