Random iteration in for loop

2019-01-28 03:50发布

问题:

I would like to make a for loop that loops through the numbers 0-8 in a random order. Note that every number can only be visited once.

How can I achieve this?

回答1:

Random r = new Random();
foreach (int i in Enumerable.Range(0, 9).OrderBy(x => r.Next()))
{
    Console.WriteLine(i);
}


回答2:

  1. Generate an array of the indices 0 to 8
  2. Shuffle the array
  3. Iterate over the array using the index at that position


回答3:

One possibility:

var numbers = Enumerable.Range(0, 9).ToList();
var rnd =  new Random();
for (; numbers.Count != 0; )
{
    var currentNumber = numbers[rnd.Next(0, numbers.Count)];

    Console.WriteLine(currentNumber);

    numbers.Remove(currentNumber); // remove current random number from list
}

Enumerable.Range(0, 9).ToList() creates a list containing the numbers from 0 to 8. Then in the loop we choose a random number from the list and remove it from the list at the end of the loop, so that the next cycle it can't be chosen again.



回答4:

Found this from a web search - Fisher-Yates shuffle, implemented in Perl.

This will generate an unbiased randomization of any input array.

sub fisher_yates_shuffle {
    my $array = shift;
    my $i;
    for ($i = @$array; --$i; ) {
        my $j = int rand ($i+1);
        next if $i == $j;
        @$array[$i,$j] = @$array[$j,$i];
    }
}

For more info:

http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

And the original I found was from:

http://perl.livejournal.com/101830.html