Generating random, unique values C#

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

    This console app will let you shuffle the alphabet five times with different orders.

    using System;
    using System.Linq;
    
    namespace Shuffle
    {
        class Program
        {
            static Random rnd = new Random();
            static void Main(string[] args)
            {
                var alphabet = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
                Console.WriteLine("Alphabet : {0}", string.Join(",", alphabet)); 
                for (int i = 0; i < 5; i++)
                {
                    var shuffledAlphabet = GetShuffledAlphabet(alphabet);
                    Console.WriteLine("SHUFFLE {0}: {1}", i, string.Join(",", shuffledAlphabet));
                }
            }
    
            static string[] GetShuffledAlphabet(string[] arr)
            {
                int?[] uniqueNumbers = new int?[arr.Length];
                string[] shuffledAlphabet = new string[arr.Length];
    
                for (int i = 0; i < arr.Length; i++)
                {
                    int uniqueNumber = GenerateUniqueNumber(uniqueNumberArrays);
                    uniqueNumberArrays[i] = uniqueNumber;
                    newArray[i] = arr[uniqueNumber];
                }
    
                return shuffledAlphabet;
            }
    
            static int GenerateUniqueNumber(int?[] uniqueNumbers)
            {
                int number = rnd.Next(uniqueNumbers.Length);
    
                if (!uniqueNumbers.Any(r => r == number))
                {
                    return number;
                }
    
                return GenerateUniqueNumber(uniqueNumbers);
            }
        }
    }
    

提交回复
热议问题