关于 产生随机数的解答

     最进,我开始找工作了,面试了几家招.net程序员的公司,做了一些面试题,发现他们的笔试题中几乎都有 求解 不重复随机数的产生问题,第一次做这道题的时候感觉题目很简单,几秒钟就做出来了,多做了几次,感觉似乎这些公司不会这么无聊吧,喜欢出这种题目,于是,便有了个心眼,尽量做出一些与其他人不同的答案,以显示自己的不同之处,下面就将自己做的几种 不同的方式答案贴出来,希望大家多讨论讨论!

    第一种解答
    ArrayList arraylist = new ArrayList();
            Random random = new Random();
            int temp = 0;
            while (arraylist.Count < 100)
            {
                temp = random.Next(1, 101);
                if (!arraylist.Contains(temp))
                {
                    arraylist.Add(temp);
                }
            }
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(arraylist[i]);
            }

 

         第二种解答

     List<int> list = new List<int>(100);
            List<int> resultList = new List<int>(100);
            for (int i = 0; i < 100; i++)
            {
                list.Add(i);
            }
            int index = 0;
            Random random = new Random();
            for (int i = 0; i < 100; i++)
            {
                index = random.Next(0, list.Count);
                resultList.Add(list[index]);
                list.Remove(list[index]);
            }

            第三种解答

    HashSet<int> hashSet = new HashSet<int>();
            Random random = new Random();
            int temp = 0;
            while (hashSet.Count < 100)
            {
                temp = random.Next(1, 101);
                hashSet.Add(temp);
            }
            foreach (var item in hashSet)
            {
                Console.WriteLine(item);
            }

 

 

    第四种(周公老师的方法)  ------最能显示自己牛逼的地方

    int[] container = new int[100];
            //用于保存返回结果  
            int[] result = new int[100];
            Random random = new Random();
            for (int i = 1; i <= 100; i++)
            {
                container[i - 1] = i;
            }
            int index = 0;
            int value = 0;
            for (int i = 0; i < 100; i++)
            {
                //从[1,container.Count + 1)中取一个随机值,保证这个值不会超过container的元素个数  
                index = random.Next(1, container.Length - 1 - i);
                //以随机生成的值作为索引取container中的值  
                value = container[index];
                //将随机取得值的放到结果集合中  
                result[i] = value;
                //将刚刚使用到的从容器集合中移到末尾去  
                container[index] = container[container.Length - i - 1];
                //将队列对应的值移到队列中  
                container[container.Length - i - 1] = value;
            }

如果各位有更好的方法 希望多交流交流~~~~

原文地址:https://www.cnblogs.com/xianrongbin/p/2230828.html