Reputation: 13
Let's say i have an array of 6 elements of int type.
It looks like this
var array = new int [] { 0, 1, 2, 3, 4, 5 };
How can I randomly shuffle my array ensuring every index have a new value.
// Bad
// The number at index 3 did not change and still has a value of 3
new int [] { 1, 0, 5, 3, 2, 4 }
// Good:
// All the index have a new value
new int [] { 4, 2, 0, 5, 3, 1 }
I've tried to Shuffle, but sometimes some values will have the same index position
Upvotes: 1
Views: 62
Reputation: 2603
You could iterate over the array and always swap with a randomly choosen index which is bigger than the current one. That way the numbers get shuffled, but no element can be shuffled back.
Edit: This acutally works, try it:
using System;
class Program {
private static Random rnd = new Random();
public static void Main() {
for (var i = 0; i < 10000; i++) {
int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Shuffle(array);
Console.WriteLine(String.Join(", ", array));
}
}
public static void Shuffle(int[] array) {
for (var i = 0; i + 1 < array.Length; i++) {
// generate j so that i < j < length
int j = rnd.Next(i + 1, array.Length);
// swap elements at i and j
var tmp = array[j];
array[j] = array[i];
array[i] = tmp;
// check
if (array[i] == i) {
throw new Exception(":(");
}
}
}
}
Also its very similar to Sattolo's algorithm, which would also work.
Upvotes: 1