在数组中随机插入数字且不重复

Posted 再叙。

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在数组中随机插入数字且不重复相关的知识,希望对你有一定的参考价值。

产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。(两种方法)

1,

     List<int> myList = new List<int>();

            Random ran = new Random();

            while (myList.Count<100)

            {

                int num = ran.Next(1, 101);

                if (!myList.Contains(num))

                {

                    myList.Add(num);

                }

            }

            foreach (int item in myList)

            {

                Console.WriteLine(item);

            }

            Console.WriteLine(myList.Count);

            Console.ReadLine();

   2,

       HashSet<int> myList = new HashSet<int>();

            Random ran = new Random();

            while (myList.Count<100)

            {

                int num = ran.Next(1, 101);

                myList.Add(num);

            }

            foreach (int item in myList)

            {

                Console.WriteLine(item);

            }

            Console.WriteLine(myList.Count);

            Console.ReadLine();

以上是关于在数组中随机插入数字且不重复的主要内容,如果未能解决你的问题,请参考以下文章