Shuffle a group of numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • akinidu
    New Member
    • May 2010
    • 7

    Shuffle a group of numbers

    Hello Every one !

    Suppose i have a vector a=[1 2 3 4 5 6 7 8 9 10]

    Now i want to shuffle these number! and produce new vector b which consist of shuffle numbers which is best way to do it !

    This problem is very similar to shuffle a group of cards!

    I have a approach in my mind like

    Take a random number from a, put it in a b in random position then choose another one from a put it randomly in b ! Question how to do it
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    That is a good approach. For the first run, you want to get a number between 0 and length of the vector - 1

    So set index = (int)(rand() * length)
    remove object at index from the first vector.
    add this object to new vector.
    repeat until the first vector is empty.

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      You could also use random_shuffle( a,a+10) which resides in the <algorithm> header file.

      Comment

      Working...