首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

如何获取100个100内的随机数不重复

2012-04-04 
怎么获取100个100内的随机数不重复获取1—100的数字,数字不重复,然后用冒泡排序。希望代码有注释。。[解决办法

怎么获取100个100内的随机数不重复
获取1—100的数字,数字不重复,然后用冒泡排序。希望代码有注释。。

[解决办法]

C# code
List<int> list = new List<int>();                while (list.Count != 100)                {                     int i = new Random().Next(1,101);                    if (!list.Contains(i))                    {                        list.Add(i);                    }                }
[解决办法]
C# code
//构造数组int[] array = new int[100];Random rand = new Random();for (int i = 0; i < 100; i++){    array[i] = i + 1;}//随机打乱顺序for (int i = 0; i < 100; i++){    int swapIndex = rand.Next(100);    int temp = array[i];    array[i] = array[swapIndex];    array[swapIndex] = temp;}//冒泡排序for (int i = 0; i < 100; i++){    for (int j = i + 1; j < 100; j++)    {        if (array[i] > array[j])        {            int temp = array[i];            array[i] = array[j];            array[j] = temp;        }    }}
[解决办法]

C# code
//这个是不是快些了  List<int> list = new List<int>();     //用于存放1-100有序的数             List<int> newList = new List<int>();  //用于存放随机出来1-100的数            for (int i = 0; i < 100; i++)            {                list.Add(i + 1);           //循环添加有循的1-100的数            }            while (list.Count != 0)            {                int index = new Random().Next(0, list.Count);  //随机出来的有序List的索引值                int flag = list[index];      //从有序List里随机出来的数                list.RemoveAt(index);  //随机出来的数从有序List里移除                newList.Add(flag);   //添加到新的List中            }
[解决办法]

C# code
 static void Main(string[] args)        {             List<int> list = new List<int>();     //用于存放1-100有序的数             List<int> newList = new List<int>();  //用于存放随机出来1-100的数            for (int i = 0; i < 100; i++)            {                list.Add(i + 1);           //循环添加有循的1-100的数            }            while (list.Count != 0)            {                int index = new Random().Next(0, list.Count);  //随机出来的有序List的索引值                int flag = list[index];      //从有序List里随机出来的数                list.RemoveAt(index);  //随机出来的数从有序List里移除                newList.Add(flag);   //添加到新的List中            }            //-----------------------下面是冒泡排序(排序的算法这个真要懂,请看看资料)--------------------------            int temp = 0;            for (int i = newList.Count; i > 0; i--)            {                for (int j = 0; j < i - 1; j++)                {                    if (newList[j] > newList[j + 1])                    {                        temp = newList[j];                        newList[j] = newList[j + 1];                        newList[j + 1] = temp;                    }                }                          }            //-------------------------这里是冒泡排序之后再输出-----------------------            for (int i = 0; i < newList.Count; i++)            {                Console.WriteLine(newList[i]);            }            Console.ReadLine();        } 

热点排行