Generating random, unique values C#

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

    You might try shuffling an array of possible ints if your range is only 0 through 9. This adds the benefit of avoiding any conflicts in the number generation.

    var nums = Enumerable.Range(0, 10).ToArray();
    var rnd = new Random();
    
    // Shuffle the array
    for (int i = 0;i < nums.Length;++i)
    {
        int randomIndex = rnd.Next(nums.Length);
        int temp = nums[randomIndex];
        nums[randomIndex] = nums[i];
        nums[i] = temp;
    }
    
    // Now your array is randomized and you can simply print them in order
    for (int i = 0;i < nums.Length;++i)
        Console.WriteLine(nums[i]);
    

提交回复
热议问题