如果我有一个整数列表:
List<int> myValues = new List<int>(new int[] { 1, 2, 3, 4, 5, 6 } );
我如何从该列表中获得 3 个随机整数?
一种简单的方法:
Random r = new Random();
IEnumerable<int> threeRandom = myValues.OrderBy(x => r.Next()).Take(3);
更好的方法:Fisher-Yates shuffle:
public static class EnumerableExtensions
{
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return source.Shuffle(new Random());
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
if (source == null) throw new ArgumentNullException("source");
if (rng == null) throw new ArgumentNullException("rng");
return source.ShuffleIterator(rng);
}
private static IEnumerable<T> ShuffleIterator<T>(
this IEnumerable<T> source, Random rng)
{
List<T> buffer = source.ToList();
for (int i = 0; i < buffer.Count; i++)
{
int j = rng.Next(i, buffer.Count);
yield return buffer[j];
buffer[j] = buffer[i];
}
}
}
你如何使用它:
IEnumerable<int> threeRandom = myValues.Shuffle().Take(3);
最简单的方法是这样的:
var r = new Random();
var myValues = new int[] { 1, 2, 3, 4, 5, 6 }; // Will work with array or list
var randomValues = Enumerable.Range(0, 3)
.Select(e => myValues[r.Next(myValues.Length)]);
但是更好的方法是,如果要确保没有重复项是使用洗牌算法,如Fisher-Yates 算法,则取前 3 项:
public static T[] Shuffle<T>(IEnumerable<T> items)
{
var result = items.ToArray();
var r = new Random();
for (int i = items.Length; i > 1; i--)
{
int j = r.Next(i);
var t = result[j];
result[j] = result[i - 1];
result[i - 1] = t;
}
return result;
}
var myValues = new int[] { 1, 2, 3, 4, 5, 6 }; // Will work with any enumerable
var randomValues = myValues.Shuffle().Take(3);
或这个:
myList.OrderBy(x => Guid.newGuid()).Take(3)
有办法做到的!一个简单的谷歌可以为您获取数百个答案。但是,您可以这样做!
myList.OrderBy(x => rnd.Next()).Take(3)
int[] x = {1,2,3,4};
string result = Convert.ToString(x[(new Random()).Next(4)]);
使用以下代码获取号码:
int k = 3; // items to select
var items = new List<int>(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
var selected = new List<int>();
var neededItem = k;
var availableItem = items.Count;
var rand = new Random();
while (selected.Count < k) {
if( rand.NextDouble() < neededItem / availableItem ) {
selected.Add(items[availableItem-1])
neededItem--;
}
availableItem--;
}