C# 从整数列表中获取随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17530306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:45:32  来源:igfitidea点击:

Getting random numbers from a list of integers

c#randomint

提问by George Harnwell

If I have a list of integers:

如果我有一个整数列表:

List<int> myValues = new List<int>(new int[] { 1, 2, 3, 4, 5, 6 } );

How would I get 3 random integers from that list?

我如何从该列表中获得 3 个随机整数?

采纳答案by Tim Schmelter

One simple way:

一种简单的方法:

Random r = new Random();
IEnumerable<int> threeRandom = myValues.OrderBy(x => r.Next()).Take(3);

The better way: Fisher–Yates shuffle:

更好的方法: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];
        }
    }
}

how you use it:

你如何使用它:

IEnumerable<int> threeRandom = myValues.Shuffle().Take(3);

回答by CodeMad

There are ways of doing it! A simple google can fetch you hundreds of answers. However, you can do this!

有办法做到的!一个简单的谷歌可以为您获取数百个答案。但是,您可以这样做!

myList.OrderBy(x => rnd.Next()).Take(3)

回答by Hyman

Use the below code to get the number:

使用以下代码获取号码:

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--;
}

回答by p.s.w.g

The simplest way would be something like this:

最简单的方法是这样的:

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)]);

But a better method, if you want to ensure there are no duplicates is to use a shuffling algorithm, like the Fisher-Yates algorithm, then take the first 3 items:

但更好的方法是,如果您想确保没有重复项,则使用改组算法,例如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);

回答by Jim Buck

Combining the other answerwith this answercan lead you to the following:

其他答案此答案结合起来可以得出以下结论:

var rand = new Random();
var numbers = Enumerable.Range(1, 6).OrderBy(i => rand.Next()).ToList();

In this case 1is the starting value (inclusive) and 6is the number of integers to generate.

在这种情况下1是起始值(包括)和6要生成的整数的数量。

回答by Peter Kellner

or this:

或这个:

myList.OrderBy(x => Guid.newGuid()).Take(3)

回答by Ali Othman

int[] x = {1,2,3,4};

string result =  Convert.ToString(x[(new Random()).Next(4)]);