Re: array random sort
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Thu, 17 Nov 2005 22:43:36 -0000
Fred Mellender <nospamPlease_fredm@xxxxxxxxxxxxxxx> wrote:
>
> "gl" <gl@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
> news:7E0D71F9-962F-4A97-9770-EC71E6659A33@xxxxxxxxxxxxxxxx
> > How do I take an array or arraylist, and sort it randomly? Like suppose
> > the
> > items in it are (1,2,3,4,5) and I want to get it to be in a random order
> > (2,3,1,4,5). How do you do that? I think it's a call to the array or array
> > lists sort method, but i'm not exactly sure how you do it.
<snip>
Note that it's relatively easy to do this *without* creating two lists
(which Fred's solution does). You can shuffle within the list, by
having an imaginary dividing line between the "randomized" section and
the "unrandomized" section of the list. You start off considering
everything to be unrandomized, then pick a random element to be element
0, swapping it if necessary.
You then take a random element *other than 0*, and swap that into
position 1.
You then take a random element *other than 0 or 1* and swap that into
position 2, etc.
Here's some code which does that with an ArrayList:
public static void Shuffle (ArrayList al)
{
for (int i=0; i < al.Count; i++)
{
object x = al[i];
int index = rng.Next(al.Count-i)+i;
al[i]=al[index];
al[index]=x;
}
}
In each iteration, we're looking to set element i (which is currently
in the "unshuffled" section) to be a random element from the unshuffled
section. At that stage, it becomes part of the shuffled section.
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.
- References:
- Re: array random sort
- From: Fred Mellender
- Re: array random sort
- Prev by Date: Re: squeeze few image files into one binary file
- Next by Date: Re: Blank Destructor - is this code okay?
- Previous by thread: Re: array random sort
- Next by thread: Re: array random sort
- Index(es):
Relevant Pages
|
Loading