Random iteration in for loop

2019-01-28 03:32发布

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?

4条回答
倾城 Initia
2楼-- · 2019-01-28 04:09
  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楼-- · 2019-01-28 04:13
Random r = new Random();
foreach (int i in Enumerable.Range(0, 9).OrderBy(x => r.Next()))
{
    Console.WriteLine(i);
}
查看更多
可以哭但决不认输i
4楼-- · 2019-01-28 04:13

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.

查看更多
成全新的幸福
5楼-- · 2019-01-28 04:21

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

查看更多
登录 后发表回答