如何从我现有的数组中创建一个随机排序的数组?就像我如何从我的旧数组中将新数组复制元素复制到新数组中,但是以随机顺序。这就是我所拥有的
MobileObjects[] array = new MobileObjects[3];
MobileObjects mob = new MobileObjects();
mob.name = ("Jawaharal");
mob.setPosition();
mob.id = 1;
array[0] = mob;
MobileObjects mob1 = new MobileObjects();
mob1.name = ("Willow");
mob1.setPosition();
mob1.id = 2;
array[1] = mob1;
MobileObjects mob2 = new MobileObjects();
mob2.name = ("Indira");
mob2.id = 3;
mob2.setPosition();
array[2] = mob2;
//shows whats in array
foreach (MobileObjects host in array)
{
Console.WriteLine("Name : " + host.name + " ");
Console.WriteLine("ID : " + host.id);
Console.WriteLine("Position: " + host.position[0] + " " +
host.position[1] + " " + host.position[2]);
}
}
答案 0 :(得分:0)
花费O(n)
时间的最佳方法是将所有元素复制到一个新数组中然后随机播放。 Fisher-Yates是标准的混洗算法,易于实现。在伪代码中:
n = myArray.length
for i=n, i>0, i--
j = randomIntegerBetween(0, i)
swap(myArray, i, j)
这显然在O(n)
中运行。实现细节将取决于您需要随机性的安全性。即使是中等大小的阵列的排列数也会远远高于大多数PRNG的周期,因此如果这成为一个问题,您将需要更好的随机源。
答案 1 :(得分:0)
您可以使用@M.Deinum m。
public static void Shuffle<T> (this Random rng, T[] array)
{
int n = array.Length;
while (n > 1)
{
int k = rng.Next(n--);
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
您可以使用基本的 Linq shuffle;
var MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray();
具有更好随机化的或 Linq
using System.Security.Cryptography;
...
RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
string[] MyRandomArray = MyArray.OrderBy(x => GetNextInt32(rnd)).ToArray();
...
static int GetNextInt32(RNGCryptoServiceProvider rnd)
{
byte[] randomInt = new byte[4];
rnd.GetBytes(randomInt);
return Convert.ToInt32(randomInt[0]);
}
注意以上2个Linq示例,是O(n log n)