Welcome to AspAdvice Sign in | Join | Help

Shuffle an ArrayList

I have a need to randomly order the contents of a collection which has as its underlying container an ArrayList.  Googling took more effort than I expected to come up with anything useful, but did yield this link.  Working from there, I came up with this method, which differs in a few ways:

public void ShuffleInPlace()
{
  ArrayList source =
this.InnerList;
  Random rnd =
new Random();
  for (int inx = source.Count-1; inx > 0; inx--)
  {
   
int position = rnd.Next(inx+1);
   
object temp = source[inx];
    source[inx] = source[position];
   
source[position] = temp;
  }
}

 The main improvements are these:

  1. The original used ArrayList.Length which wasn't defined, so I converted to ArrayList.Count.
  2. The original was a static and took an ArrayList as a parameter (named source) -- I refactored it to work as an instance method within the collection.
  3. The original had a bug in it where it generated the random number.  I corrected it by adding +1 to the rnd.Next() call.  You can reproduce the bug by shuffling a 3-element array with the original algorithm.  The item that begins in position 2 will never be in position 2 after shuffling (and I think the same is true for positions 1 and 3, but now that I've fixed it I don't care enough to verify that).
Sponsor
Published Thursday, January 27, 2005 5:19 PM by ssmith
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Shuffle an ArrayList

i had the same error in my "shuffleList" method, the last item was never shuffled. It works with the rnd.Next(inx+1), cheers
Thursday, December 01, 2005 9:06 AM by mark

# re: Shuffle an ArrayList

Thats no shuffle algorithmn!

You have to select step by step one element and put them into a new list.

Monday, February 12, 2007 1:36 PM by Tiger

# re: Shuffle an ArrayList

Use this one:

private void ShuffleArrayList(ref ArrayList source)

{

ArrayList target = new ArrayList(source.Count);

Random rnd = new Random();

while(source.Count>0)

{

int idx = rnd.Next(source.Count);

target.Add(source[idx]);

source.RemoveAt(idx);

}

source = target;

}

Monday, February 12, 2007 1:45 PM by Tieger

# re: Shuffle an ArrayList

Looking at topmost code snippet I wonder: does "inx" ever become 0?

This would mean that you never 'actively' swap the card that is located there. Only when "position" = 0, you end up with a change at that location.

Monday, March 31, 2008 9:06 AM by rednaxela

# Shuffle Extension Method für IList<T>

Ich schreibe momentan eine kleine Anwendung und ben&#246;tige hierf&#252;r eine zuf&#228;llig durcheinandergeworfene

Thursday, May 08, 2008 7:14 AM by Dariusz quatscht

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below