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?
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?
Random r = new Random();
foreach (int i in Enumerable.Range(0, 9).OrderBy(x => r.Next()))
{
Console.WriteLine(i);
}
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.
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