以随机顺序返回整数数组的函数

时间:2014-07-24 10:51:48

标签: .net arrays function random integer

我需要编写一个函数,它返回一个整数数组,其中1000个元素按随机顺序包含值1到1000。没有省略或重复的数字。

到目前为止,我有:

private static void RandomNum()
    {
        //Initialize an array
        int[] randomList = new int[1000];
        //Initialize an instance of random class
        Random rnd = new Random();
        // integer variable
        int counter = 0;





            while (counter < 1000)
            {
                //store random num 
                int random = rnd.Next(1, 1001);


                if (Array.IndexOf(randomList, random) <= 0)
                {
                    //store random number into Array
                    randomList[counter] = random;
                    counter++;
                }




            }


        //output elements in Array
        for (int i = 0; i < 1000; i++)
        {
            Console.WriteLine(randomList[i]);
        }
        //output number of elements in Array
        Console.WriteLine(counter);
        Console.Read();
    }

1 个答案:

答案 0 :(得分:0)

// Pseudocode

HashSet<int> uniqueValues = new HashSet<int>();
while(uniqueValues.Count < 1000)
{
    uniqueValues.Add(Random.Next(1,1001));
}