予有二维阵列。我想选择一个插槽随意,并继续这样做从来没有采摘相同的插槽两次,直到我终于拿起所有插槽(所以没有随机对最后挑课程)。有一个众所周知的算法,这样做呢?我使用C#,但很明显这是更多的算法比任何特定的平台。是的,'大书'是我的购买清单:)
I have two dimensional array. I want to pick a slot at random, and continue to do so never picking the same slot twice until I have finally picked all slots (so nothing random about the last pick of course). Is there a well known algorithm for doing this? I'm using C#, but obviously this is more about algorithms than any particular platform. Yes, 'the big book' is on my purchase list :)
使用费雪耶茨洗牌算法前面提到的(在O(n)时间)
Using the Fisher-Yates shuffle algorithm as mentioned before (in O(n) time)
int X = 3; int Y = 4;
int[] array = new int[X * Y];
for (int i = 0; i < array.Length; i++) array[i] = i;
FisherYatesShuffle(array);
var randomSlots = array.Select((i,j) => new {x=array[j]%X , y=array[j]/X })
.ToArray();
public static void FisherYatesShuffle<T>(T[] array)
{
Random r = new Random();
for (int i = array.Length - 1; i > 0; i--)
{
int j = r.Next(0, i + 1);
T temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}