【发布时间】:2014-08-18 10:46:00
【问题描述】:
我正在阅读算法简介 - 第三版,现在,我必须实现 RANDOMIZE-IN-PLACE 算法,该算法必须置换当前数组中的每个值。 本书提供的伪代码如下:
n = A.length
for i = 1 to n
swap A[i] with A[Random(i, n)]
我尝试在 C# 上实现该功能,但有时会收到 IndexOutOfRangeException(仅在某些情况下)。我曾经调试过算法,发现当
randomValue = array[randomNumber.Next(index, upperBound)];
index 等于array.Length - 1 并且upperBound 是array.Length - 1 (换句话说index 和upperBound 是相同的值并且.Next 看起来像这样.Next(9, 9) 例如),随机生成器能够产生数字10(下限/上限+ 1)正是我的array.Length。如果有人知道如何解决这将对我非常有帮助。再次感谢。这是我的 C# 代码。
namespace RandomizedAlgorithms
{
using System;
class RandomizeInPlace
{
static void Main()
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Randomize(array);
for (int index = 0; index <= array.Length - 1 ; index++)
{
Console.WriteLine(array[index]);
}
}
private static void Randomize(int[] array)
{
Random randomNumber = new Random();
int swapVariable = 0;
int randomValue = 0;
int upperBound = array.Length - 1;
for (int index = 0; index <= array.Length - 1 ; index++)
{
randomValue = array[randomNumber.Next(index, upperBound)];
swapVariable = array[randomValue];
array[randomValue] = array[index];
array[index] = swapVariable;
}
}
}
}
【问题讨论】:
-
@MitchWheat 是 Fisher-Yates,如果我没记错的话
-
您不需要将最后一个值与自身交换。
-
但是根据伪代码,你希望 .Next 像 (currentPosition, TotalAmountOfItems) :/
-
@NahuelIanni 注意
upperBound = array.Length - 1,本质上是TotalAmountOfItems -
请注意
Random.Next(int)的上限是独占的。'The exclusive upper bound of the random number to be generated.'(msdn.microsoft.com/en-us/library/zd1bc8e5%28v=vs.110%29.aspx)。这意味着您应该使用int upperBound = array.Length;