Generate N random and unique numbers within a range

后端 未结 7 2008
不知归路
不知归路 2020-11-27 07:50

What is an efficient way of generating N unique numbers within a given range using C#? For example, generate 6 unique numbers between 1 and 50. A lazy way would be to simply

7条回答
  •  迷失自我
    2020-11-27 08:15

    For large sets of unique numbers, put them in an List..

            Random random = new Random();
            List uniqueInts = new List(10000);
            List ranInts = new List(500);
            for (int i = 1; i < 10000; i++) { uniqueInts.Add(i); }
    
            for (int i = 1; i < 500; i++)
            {
                int index = random.Next(uniqueInts.Count) + 1;
                ranInts.Add(uniqueInts[index]);
                uniqueInts.RemoveAt(index);
            }
    

    Then randomly generate a number from 1 to myInts.Count. Store the myInt value and remove it from the List. No need to shuffle the list nor look to see if the value already exists.

提交回复
热议问题