Non-repetitive random number

后端 未结 10 1934
囚心锁ツ
囚心锁ツ 2020-11-27 08:10

To generate Random numbers from 1- 20 I need to pick selective and it should not be repetitive.

How to do this in C#

Note I need to loop through as like this

10条回答
  •  无人及你
    2020-11-27 09:03

    An IEnumerable implementation, based on Hallgrim's answer:

    public class UniqueRandoms : IEnumerable
    {
        Random _rand = new Random();
        List _candidates;
    
        public UniqueRandoms(int maxInclusive)
            : this(1, maxInclusive)
        { }
    
        public UniqueRandoms(int minInclusive, int maxInclusive)
        {
            _candidates = 
                Enumerable.Range(minInclusive, maxInclusive - minInclusive + 1).ToList();
        }
    
        public IEnumerator GetEnumerator()
        {
            while (_candidates.Count > 0)
            {
                int index = _rand.Next(_candidates.Count);
                yield return _candidates[index];
                _candidates.RemoveAt(index);
            }
        }
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    

提交回复
热议问题