Generating random, unique values C#

前端 未结 17 1171
佛祖请我去吃肉
佛祖请我去吃肉 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 15:12

    Depending on what you are really after you can do something like this:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace SO14473321
    {
        class Program
        {
            static void Main()
            {
                UniqueRandom u = new UniqueRandom(Enumerable.Range(1,10));
                for (int i = 0; i < 10; i++)
                {
                    Console.Write("{0} ",u.Next());
                }
            }
        }
    
        class UniqueRandom
        {
            private readonly List _currentList;
            private readonly Random _random = new Random();
    
            public UniqueRandom(IEnumerable seed)
            {
                _currentList = new List(seed);
            }
    
            public int Next()
            {
                if (_currentList.Count == 0)
                {
                    throw new ApplicationException("No more numbers");
                }
    
                int i = _random.Next(_currentList.Count);
                int result = _currentList[i];
                _currentList.RemoveAt(i);
                return result;
            }
        }
    }
    

提交回复
热议问题