// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Linq; namespace E { public class Program { private static Random rng = new Random(); public static List Bad(int n, int min, int max) { List res = new List(); for(int i = 0; i < n; i++) { res.Add(rng.Next(min, max + 1)); } return res; } public static List Good1(int n, int min, int max) { List res = new List(); for(int i = 0; i < n; i++) { int v; do { v = rng.Next(min, max + 1); } while(res.Contains(v)); res.Add(v); } return res; } public static List Good2(int n, int min, int max) { List res = new List(); for(int i = min; i <= max; i++) { res.Add(i); } return res.Select(v => new Tuple(v, rng.Next())).OrderBy(r => r.Item2).Select(r => r.Item1).Take(n).ToList(); } public static void Main(string[] args) { Console.WriteLine("Wrong:"); foreach(int v in Bad(5, 1, 10)) { Console.WriteLine(v); } Console.WriteLine("Check for duplicate:"); foreach(int v in Good1(5, 1, 10)) { Console.WriteLine(v); } Console.WriteLine("Shuffle:"); foreach(int v in Good2(5, 1, 10)) { Console.WriteLine(v); } } } }