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.