Results 1 to 3 of 3

Thread: How to randomly shuffle the elements within a QValueVector/QValueList?

  1. #1
    Join Date
    Nov 2006
    Posts
    58
    Thanks
    1
    Qt products
    Qt3
    Platforms
    Unix/X11

    Default How to randomly shuffle the elements within a QValueVector/QValueList?

    Let's say, I defined a QValueVector or QValueList with "int" type elements and also put some elements into the vector/list to fulfill the stucture. Then, I need a function that can randomly shuffle the elements' sequence which is already stored in my vector/list.

    Is there some available methods provided by Qt3 to do this kind of work?
    BTW: I have searched through the Qt's documents, but I failed to get such functions.

    Thanks a lot.

  2. #2
    Join Date
    Feb 2006
    Location
    Romania
    Posts
    2,744
    Thanks
    8
    Thanked 541 Times in 521 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: How to randomly shuffle the elements within a QValueVector/QValueList?

    See STL's next_permutation. But you could also create a simple algorithm of your own to generate a random permutation.

    For example, if you have N elements in your initial vector, then allocate another int vector with N elements and for each index assign an random integer between 0..N-1, but make sure this is unique by testing with the previous elements. Next rearrange the elements in the first vector according to this order:
    Qt Code:
    1. int x[] = {1, 2, 3, 4, 5};
    2. ...
    3. int perm[] = {0, 2, 1, 4, 3 }
    To copy to clipboard, switch view to plain text mode 
    This would yield x = { 1, 3, 2, 5, 4 }

    This is just to get you started. You could do without the second array.

  3. #3
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,364
    Thanks
    3
    Thanked 5,012 Times in 4,791 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: How to randomly shuffle the elements within a QValueVector/QValueList?

    The easiest way is to simply call std::shuffle() on the container.

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.