我张贴正确执行洗牌的算法,因为另一张贴在这里不生产一个统一的洗牌。
正如其他答案所述,对于少量要随机化的值,您可以简单地使用这些值填充数组,然后使用数组,然后使用所需的许多值。
以下是Fisher-Yates Shuffle(又名Knuth Shuffle)的实现。 (阅读该链接的“实现错误”部分(搜索“总是从每次迭代中的整个有效数组索引中选择j”),以查看关于此处发布的其他实现的错误的一些讨论。)
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
static class Program
{
static void Main(string[] args)
{
Shuffler shuffler = new Shuffler();
List<int> list = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
shuffler.Shuffle(list);
foreach (int value in list)
{
Console.WriteLine(value);
}
}
}
/// <summary>Used to shuffle collections.</summary>
public class Shuffler
{
/// <summary>Creates the shuffler with a <see cref="MersenneTwister"/> as the random number generator.</summary>
public Shuffler()
{
_rng = new Random();
}
/// <summary>Shuffles the specified array.</summary>
/// <typeparam name="T">The type of the array elements.</typeparam>
/// <param name="array">The array to shuffle.</param>
public void Shuffle<T>(IList<T> array)
{
for (int n = array.Count; n > 1;)
{
int k = _rng.Next(n);
--n;
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
private System.Random _rng;
}
}
http://csharpindepth.com/Articles/Chapter12/Random.aspx – Habib
只要你只是创建Random对象一次,你不应该有问题。如果你想要的数字是唯一的(还没有这个数字),那么你需要添加额外的,而不仅仅是使用随机 – RoneRackal
你在寻找“数字1..10排列”而不是“随机数在范围1..10“? (Definiitely给你随机序列10个唯一的数字) –