Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Shortest Way to Shuffle Array

Shortest Way to Shuffle Array

Scheduled Pinned Locked Moved C#
data-structures
15 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    computerpublic
    wrote on last edited by
    #1

    /*I am trying to find the absolute shortest way to shuffle the following array. I saw many different methods on the MSDN and Google Search, but no one show a short method of completley (ramdom, no order) shuffling an array.*/

                    int\[\] array = {1,2,3,4,5};
                    for (int i = 0; i < 5; i++)
                        Console.WriteLine("{0}", array\[i\]);
    
    B G P H 5 Replies Last reply
    0
    • C computerpublic

      /*I am trying to find the absolute shortest way to shuffle the following array. I saw many different methods on the MSDN and Google Search, but no one show a short method of completley (ramdom, no order) shuffling an array.*/

                      int\[\] array = {1,2,3,4,5};
                      for (int i = 0; i < 5; i++)
                          Console.WriteLine("{0}", array\[i\]);
      
      B Offline
      B Offline
      BillWoodruff
      wrote on last edited by
      #2

      I prefer to use a Generic method to handle sorting any Type:

      private T[] ShuffleArray<T>(T[] theArray)
      {
      Random rnd = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
      return theArray.OrderBy(itm => rnd.Next()).ToArray();
      }

      Examples of use:

      int[] theInts = new int[]{1,2,3,4,5};

      theInts = ShuffleArray(theInts);

      string[] theStrings = new string[] {"a", "b", "c", "d","e","f"};

      theStrings = ShuffleArray(theStrings);

      I used the code in this 2008 StackOverFlow thread for the shuffling routine shown here, but adapted it myself to be generic: [^]. I strongly suggest you study that SO thread; it has a variety of techniques presented, and good discussion of issues. The technique I'm using here is not as "powerful," and fast, as other techniques: your specific Application may need/require stronger methods, including, possibly, the use of the Cryptographic Random generator in .NET; see: [^] for an example that uses 'OrderBy with the Cryptographic Random generator.

      “The best hope is that one of these days the Ground will get disgusted enough just to walk away ~ leaving people with nothing more to stand ON than what they have so bloody well stood FOR up to now.” Kenneth Patchen, Poet

      S C B 3 Replies Last reply
      0
      • C computerpublic

        /*I am trying to find the absolute shortest way to shuffle the following array. I saw many different methods on the MSDN and Google Search, but no one show a short method of completley (ramdom, no order) shuffling an array.*/

                        int\[\] array = {1,2,3,4,5};
                        for (int i = 0; i < 5; i++)
                            Console.WriteLine("{0}", array\[i\]);
        
        G Offline
        G Offline
        GuyThiebaut
        wrote on last edited by
        #3

        You might want to check the Computerphile channel on youtube who do a number of very good presentations on sorting arrays(I take it when you say shuffle you mean sort). The short answer is that there is no fastest method that fits all scenarios - depending on the number of elements and distribution different methods will be faster or slower. The main factor influencing which sort algorithm to use is the size of the array.

        “That which can be asserted without evidence, can be dismissed without evidence.”

        ― Christopher Hitchens

        B C 2 Replies Last reply
        0
        • G GuyThiebaut

          You might want to check the Computerphile channel on youtube who do a number of very good presentations on sorting arrays(I take it when you say shuffle you mean sort). The short answer is that there is no fastest method that fits all scenarios - depending on the number of elements and distribution different methods will be faster or slower. The main factor influencing which sort algorithm to use is the size of the array.

          “That which can be asserted without evidence, can be dismissed without evidence.”

          ― Christopher Hitchens

          B Offline
          B Offline
          BillWoodruff
          wrote on last edited by
          #4

          The use of the word "random" indicates the question is, indeed, about shuffling, not sorting.

          “The best hope is that one of these days the Ground will get disgusted enough just to walk away ~ leaving people with nothing more to stand ON than what they have so bloody well stood FOR up to now.” Kenneth Patchen, Poet

          1 Reply Last reply
          0
          • B BillWoodruff

            I prefer to use a Generic method to handle sorting any Type:

            private T[] ShuffleArray<T>(T[] theArray)
            {
            Random rnd = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
            return theArray.OrderBy(itm => rnd.Next()).ToArray();
            }

            Examples of use:

            int[] theInts = new int[]{1,2,3,4,5};

            theInts = ShuffleArray(theInts);

            string[] theStrings = new string[] {"a", "b", "c", "d","e","f"};

            theStrings = ShuffleArray(theStrings);

            I used the code in this 2008 StackOverFlow thread for the shuffling routine shown here, but adapted it myself to be generic: [^]. I strongly suggest you study that SO thread; it has a variety of techniques presented, and good discussion of issues. The technique I'm using here is not as "powerful," and fast, as other techniques: your specific Application may need/require stronger methods, including, possibly, the use of the Cryptographic Random generator in .NET; see: [^] for an example that uses 'OrderBy with the Cryptographic Random generator.

            “The best hope is that one of these days the Ground will get disgusted enough just to walk away ~ leaving people with nothing more to stand ON than what they have so bloody well stood FOR up to now.” Kenneth Patchen, Poet

            S Offline
            S Offline
            Simon_Whale
            wrote on last edited by
            #5

            Interesting link provided

            Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

            C 1 Reply Last reply
            0
            • B BillWoodruff

              I prefer to use a Generic method to handle sorting any Type:

              private T[] ShuffleArray<T>(T[] theArray)
              {
              Random rnd = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
              return theArray.OrderBy(itm => rnd.Next()).ToArray();
              }

              Examples of use:

              int[] theInts = new int[]{1,2,3,4,5};

              theInts = ShuffleArray(theInts);

              string[] theStrings = new string[] {"a", "b", "c", "d","e","f"};

              theStrings = ShuffleArray(theStrings);

              I used the code in this 2008 StackOverFlow thread for the shuffling routine shown here, but adapted it myself to be generic: [^]. I strongly suggest you study that SO thread; it has a variety of techniques presented, and good discussion of issues. The technique I'm using here is not as "powerful," and fast, as other techniques: your specific Application may need/require stronger methods, including, possibly, the use of the Cryptographic Random generator in .NET; see: [^] for an example that uses 'OrderBy with the Cryptographic Random generator.

              “The best hope is that one of these days the Ground will get disgusted enough just to walk away ~ leaving people with nothing more to stand ON than what they have so bloody well stood FOR up to now.” Kenneth Patchen, Poet

              C Offline
              C Offline
              computerpublic
              wrote on last edited by
              #6

              Your solution doesn't really help me. I want to shuffle the contents INSIDE the array. So when I index array[0], the value at index array[0] should always be different.

              1 Reply Last reply
              0
              • S Simon_Whale

                Interesting link provided

                Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

                C Offline
                C Offline
                computerpublic
                wrote on last edited by
                #7

                This is a very very funny. But it doesn't help me. lol..

                S 1 Reply Last reply
                0
                • G GuyThiebaut

                  You might want to check the Computerphile channel on youtube who do a number of very good presentations on sorting arrays(I take it when you say shuffle you mean sort). The short answer is that there is no fastest method that fits all scenarios - depending on the number of elements and distribution different methods will be faster or slower. The main factor influencing which sort algorithm to use is the size of the array.

                  “That which can be asserted without evidence, can be dismissed without evidence.”

                  ― Christopher Hitchens

                  C Offline
                  C Offline
                  computerpublic
                  wrote on last edited by
                  #8

                  I don't want to sort. I want to shuffle (mixed up, disorganize).

                  1 Reply Last reply
                  0
                  • C computerpublic

                    This is a very very funny. But it doesn't help me. lol..

                    S Offline
                    S Offline
                    Simon_Whale
                    wrote on last edited by
                    #9

                    I replied to Bill stating that it was a good link as I personally found it a good read and some of the links inside are also worth reading Bill also showed you a good method of shuffling the array.

                    Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

                    C 1 Reply Last reply
                    0
                    • S Simon_Whale

                      I replied to Bill stating that it was a good link as I personally found it a good read and some of the links inside are also worth reading Bill also showed you a good method of shuffling the array.

                      Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

                      C Offline
                      C Offline
                      computerpublic
                      wrote on last edited by
                      #10

                      I don't understand his example. I have been playing with it all morning. I am very new to this and I am trying to learn. I simply want to move the around the contents randomly.

                      int[] array = {1,2,3,4,5};
                      for (int i = 0; i < 5; i++)
                      Console.WriteLine("{0}", array[i]);

                      S 1 Reply Last reply
                      0
                      • C computerpublic

                        I don't understand his example. I have been playing with it all morning. I am very new to this and I am trying to learn. I simply want to move the around the contents randomly.

                        int[] array = {1,2,3,4,5};
                        for (int i = 0; i < 5; i++)
                        Console.WriteLine("{0}", array[i]);

                        S Offline
                        S Offline
                        Simon_Whale
                        wrote on last edited by
                        #11

                        //Create out array
                        int[] arrayValues = {1,2,3,4,5,6};

                        //Create a random value
                        Random rnd = new Random((int)DateTime.Now.Ticks & 0x0000FFFF);

                        //Do the Shuffle, using Linq which returns an object of IEnumerable in this case
                        // so we need to convert to back to an array hence to ".ToArray()" at the end.
                        arrayValues = arrayValue.Orderby(itm => rnd.Next()).ToArray();

                        have a read of these, as the solution covers a range of topics but does what you are after. I am afraid to say that you are going to have do some background reading to get yourself up to speed. datetime.now.ticks[^] LINQ Tutorial for Beginners[^]

                        Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

                        1 Reply Last reply
                        0
                        • C computerpublic

                          /*I am trying to find the absolute shortest way to shuffle the following array. I saw many different methods on the MSDN and Google Search, but no one show a short method of completley (ramdom, no order) shuffling an array.*/

                                          int\[\] array = {1,2,3,4,5};
                                          for (int i = 0; i < 5; i++)
                                              Console.WriteLine("{0}", array\[i\]);
                          
                          P Offline
                          P Offline
                          Pete OHanlon
                          wrote on last edited by
                          #12

                          When you express a problem, it's helpful to think in terms of what you are actually trying to solve. So, when you say the shortest way, this could mean many different things. Do you mean that, given an arbitrarily large array, you want the fastest shuffle? Should it be the fewest number of lines? Any of a half dozen other possible meanings of shortest? You will get a lot of guesses and assumptions about what the problem is that you are trying to solve - especially when you show a code snippet that doesn't have any real relation to the problem other than it's got an array in it.

                          1 Reply Last reply
                          0
                          • B BillWoodruff

                            I prefer to use a Generic method to handle sorting any Type:

                            private T[] ShuffleArray<T>(T[] theArray)
                            {
                            Random rnd = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
                            return theArray.OrderBy(itm => rnd.Next()).ToArray();
                            }

                            Examples of use:

                            int[] theInts = new int[]{1,2,3,4,5};

                            theInts = ShuffleArray(theInts);

                            string[] theStrings = new string[] {"a", "b", "c", "d","e","f"};

                            theStrings = ShuffleArray(theStrings);

                            I used the code in this 2008 StackOverFlow thread for the shuffling routine shown here, but adapted it myself to be generic: [^]. I strongly suggest you study that SO thread; it has a variety of techniques presented, and good discussion of issues. The technique I'm using here is not as "powerful," and fast, as other techniques: your specific Application may need/require stronger methods, including, possibly, the use of the Cryptographic Random generator in .NET; see: [^] for an example that uses 'OrderBy with the Cryptographic Random generator.

                            “The best hope is that one of these days the Ground will get disgusted enough just to walk away ~ leaving people with nothing more to stand ON than what they have so bloody well stood FOR up to now.” Kenneth Patchen, Poet

                            B Offline
                            B Offline
                            BobJanova
                            wrote on last edited by
                            #13

                            Using OrderBy with a random number generator is a good trick.

                            1 Reply Last reply
                            0
                            • C computerpublic

                              /*I am trying to find the absolute shortest way to shuffle the following array. I saw many different methods on the MSDN and Google Search, but no one show a short method of completley (ramdom, no order) shuffling an array.*/

                                              int\[\] array = {1,2,3,4,5};
                                              for (int i = 0; i < 5; i++)
                                                  Console.WriteLine("{0}", array\[i\]);
                              
                              H Offline
                              H Offline
                              Henrik Jonsson
                              wrote on last edited by
                              #14

                              This generic function provides a quick way of randomly shuffling (reordering) the items in-place in an existing array:

                              public static void ShuffleArray(T[] array)
                              {
                              Random rnd = new Random();
                              int[] order = new int[array.Length];
                              for (int i = 0; i < array.Length; i++)
                              {
                              order[i] = rnd.Next();
                              }
                              Array.Sort(order, array);
                              }

                              It can we rewritten as

                              Random rnd = new Random();
                              Array.Sort(array.Select(r => rnd.Next()).ToArray(), array);

                              giving just slightly worse performance. According to my tests the use of Array.Sort is about three times faster than the OrderBy solution for a million integer array.

                              1 Reply Last reply
                              0
                              • C computerpublic

                                /*I am trying to find the absolute shortest way to shuffle the following array. I saw many different methods on the MSDN and Google Search, but no one show a short method of completley (ramdom, no order) shuffling an array.*/

                                                int\[\] array = {1,2,3,4,5};
                                                for (int i = 0; i < 5; i++)
                                                    Console.WriteLine("{0}", array\[i\]);
                                
                                H Offline
                                H Offline
                                Henrik Jonsson
                                wrote on last edited by
                                #15

                                Hi again, using the Fisher-Yates shuffling algorithm [^] seems to be superior in performance:

                                public static void Shuffle(T[] array)
                                {
                                Random rnd = new Random();
                                for (int i = array.Length - 1; i >= 0; i--)
                                {
                                int index = rnd.Next(i);
                                T temp = array[index];
                                array[index] = array[i];
                                array[i] = temp;
                                }
                                }

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups