Getting random numbers from a list of integers

2020-07-07 11:19发布

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?

标签: c# random int
7条回答
混吃等死
2楼-- · 2020-07-07 11:55

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--;
}
查看更多
欢心
3楼-- · 2020-07-07 12:03

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:

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);
查看更多
欢心
4楼-- · 2020-07-07 12:04

or this:

myList.OrderBy(x => Guid.newGuid()).Take(3)
查看更多
闹够了就滚
5楼-- · 2020-07-07 12:05

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)
查看更多
Fickle 薄情
6楼-- · 2020-07-07 12:06

One simple way:

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

The better way: 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);
查看更多
兄弟一词,经得起流年.
7楼-- · 2020-07-07 12:11

Combining the other answer with this answer can lead you to the following:

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

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

查看更多
登录 后发表回答