Generating random, unique values C#

前端 未结 17 1157
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:26

I\'ve searched for a while and been struggling to find this, I\'m trying to generate several random, unique numbers is C#. I\'m using System.Random, and I\'m us

17条回答
  •  无人及你
    2020-11-22 14:53

    I noted that the accepted answer keeps adding int to the list and keeps checking them with if (!randomList.Contains(MyNumber)) and I think this doesn't scale well, especially if you keep asking for new numbers.

    I would do the opposite.

    1. Generate the list at startup, linearly
    2. Get a random index from the list
    3. Remove the found int from the list

    This would require a slightly bit more time at startup, but will scale much much better.

    public class RandomIntGenerator
    {
        public Random a = new Random();
        private List _validNumbers;
    
        private RandomIntGenerator(int desiredAmount, int start = 0)
        {
            _validNumbers = new List();
            for (int i = 0; i < desiredAmount; i++)
                _validNumbers.Add(i + start);
        }
    
        private int GetRandomInt()
        {
            if (_validNumbers.Count == 0)
            {
                //you could throw an exception here
                return -1;
            }
            else
            {
                var nextIndex = a.Next(0, _validNumbers.Count - 1);
                var number    = _validNumbers[nextIndex];
                _validNumbers.RemoveAt(nextIndex);
                return number;
            }
        }
    }
    

提交回复
热议问题