Non-repetitive random number

后端 未结 10 1884
囚心锁ツ
囚心锁ツ 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:09

    Just like i did:

        list.Clear();
        int count = 0;
        
        while (count < 20)
        {            
            int x = Random.Range(1, 21);
            if (!list.Contains(x))
            {
                list.Add(x);
                count++;
            }
        }
    
    0 讨论(0)
  • 2020-11-27 09:11
    class Program
    {
        static void Main(string[] args)
        {        
            List<int> list = new List<int>();
            int val;
            Random r;
            int IntialCount = 1;
            int count = 7 ;
            int maxRandomValue = 8;
    
            while (IntialCount <= count)
            {
                r = new Random();
                val = r.Next(maxRandomValue);
                if (!list.Contains(val))
                {
                    list.Add(val);
                    IntialCount++;
                }
    
            } 
        }
    }
    
    0 讨论(0)
  • 2020-11-27 09:15
    static void Main(string[] args)
    {
        //Randomize 15 numbers out of 25 - from 1 to 25 - in ascending order
        var randomNumbers = new List<int>();
        var randomGenerator = new Random();
        int initialCount = 1;
    
        for (int i = 1; i <= 15; i++)
        {
            while (initialCount <= 15)
            {
                int num = randomGenerator.Next(1, 26);
                if (!randomNumbers.Contains(num))
                {
                    randomNumbers.Add(num);
                    initialCount++;
                }
            }
        }
        randomNumbers.Sort();
        randomNumbers.ForEach(x => Console.WriteLine(x));
    }
    
    0 讨论(0)
  • 2020-11-27 09:17

    This method will generate all the numbers, and no numbers will be repeated:

    /// <summary>
    /// Returns all numbers, between min and max inclusive, once in a random sequence.
    /// </summary>
    IEnumerable<int> UniqueRandom(int minInclusive, int maxInclusive)
    {
        List<int> candidates = new List<int>();
        for (int i = minInclusive; i <= maxInclusive; i++)
        {
            candidates.Add(i);
        }
        Random rnd = new Random();
        while (candidates.Count > 0)
        {
            int index = rnd.Next(candidates.Count);
            yield return candidates[index];
            candidates.RemoveAt(index);
        }
    }
    

    You can use it like this:

    Console.WriteLine("All numbers between 0 and 20 in random order:");
    foreach (int i in UniqueRandom(0, 20)) {
        Console.WriteLine(i);
    }
    
    0 讨论(0)
提交回复
热议问题