Randomize array items

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm trying to determine the best way to randomize a set of array items. I'm
thinking that I could use an arraylist and have it use the lower and upper
bounds as the limits. Any suggestions?

Cheers,
Steve
 
Fieldmedic said:
I'm trying to determine the best way to randomize a set of array items. I'm
thinking that I could use an arraylist and have it use the lower and upper
bounds as the limits. Any suggestions?

There's no need to use an ArrayList - the size doesn't need to change.

Here's a method which will actually shuffle *any* IList:

static Random rng = new Random();
static void Randomize(IList list)
{

for (int i=list.Count-1; i > 0; i--)

{
int swapIndex = rng.Next(i+1);
if (swapIndex != i)
{
object tmp = list[swapIndex];
list[swapIndex] = list;
list = tmp;
}
}
}

The way it works is to mentally divide the list into two halves - the
unshuffled half (in the range [0,i]) and the shuffled half (in the
range [i+1, list.Count-1]).

In each iteration, it picks a random element from the unshuffled half,
and swaps it with the element at the end of the unshuffled half, then
moves the boundary down.

Note that if you're shuffling arrays of value types, you should use a
strongly typed version of the above, changing the declaration of both
list and tmp appropriately, to avoid boxing.
 
Jon,
Thanks for the input! The reason I was thinking arraylist was because
the "list" of items will actually come from the selected items in a ListBox.
The ListBox connects to a database and the user can select from the items in
it to narrow create the list of items to be randomized. I'll give your code a
shot, although I have to convert it to VB. :)

Thanks again,
Steve


Jon Skeet said:
Fieldmedic said:
I'm trying to determine the best way to randomize a set of array items. I'm
thinking that I could use an arraylist and have it use the lower and upper
bounds as the limits. Any suggestions?

There's no need to use an ArrayList - the size doesn't need to change.

Here's a method which will actually shuffle *any* IList:

static Random rng = new Random();
static void Randomize(IList list)
{

for (int i=list.Count-1; i > 0; i--)

{
int swapIndex = rng.Next(i+1);
if (swapIndex != i)
{
object tmp = list[swapIndex];
list[swapIndex] = list;
list = tmp;
}
}
}

The way it works is to mentally divide the list into two halves - the
unshuffled half (in the range [0,i]) and the shuffled half (in the
range [i+1, list.Count-1]).

In each iteration, it picks a random element from the unshuffled half,
and swaps it with the element at the end of the unshuffled half, then
moves the boundary down.

Note that if you're shuffling arrays of value types, you should use a
strongly typed version of the above, changing the declaration of both
list and tmp appropriately, to avoid boxing.
 
Back
Top