【问题标题】:function that returns an array of integers in random order以随机顺序返回整数数组的函数
【发布时间】:2014-09-15 21:19:56
【问题描述】:

我需要编写一个函数,它返回一个包含 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();
    }

【问题讨论】:

  • 这称为随机播放。算法可以在维基百科上找到。
  • 到目前为止我有:随机 rnd=new Random(); string[] MyRandomArray = MyArray.OrderBy(x => rnd.Next(1,1000)).ToArray();
  • 那么剩下的问题是什么?但也要寻找就地算法 (Yates)。
  • “我的回答应该表现出良好的编程风格、技术以及对准确性和性能的关注” - 抱歉,但看起来像是面试或家庭作业。您的答案是否应该包括来自 StackOverflow 的支持?
  • “不想使用内部数据类型之外的其他 .Net 框架类(即不想使用集合)”——这似乎是矛盾的,集合是“固有的”.NET fata 类型.

标签: .net arrays function random integer


【解决方案1】:

// 伪代码

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

【讨论】:

    猜你喜欢
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 2012-04-25
    • 2014-11-16
    相关资源
    最近更新 更多