In this example you will learn how to make “Random number generator with no duplicates from a list ” in C# language.
Lastday I was faced with the task of getting as many random elements as possible from a list. In this case, no random element should be returned twice. For this I have written a generic extension method. In the extension method, all elements are mixed first. Then random items are fetched from the mixed list with a for loop.
If there are fewer elements in the list than requested, then only as many elements are returned as there are.
Here is a sample call:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
List<int> list = new List<int>(); list.Add(1); list.Add(2); list.Add(3); list.Add(4); list.Add(5); list.Add(6); list.Add(7); list.Add(8); list.Add(9); list.Add(10); list = list.GetRandomItems(8); for (int i = 0; i < list.Count; i++) Console.Write(list[i] + " "); Console.Read(); |
The output would be for example:
4 3 1 7 8 2 9 5
Here is solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public static class ListExtensions { private static Random rnd = new Random(); public static List<T> GetRandomItems<T>(this IList<T> list, int maxCount) { List<T> resultList = new List<T>(); list.Shuffle(); for (int i = 0; i < maxCount && i < list.Count; i++) resultList.Add(list[i]); return resultList; } private static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rnd.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } } |