C # generate a random index list,

Source: Internet
Author: User

C # generate a random index list,

/// <Summary> /// generate a random index list /// </summary> /// <param name = "maxNumber"> </param> /// <returns> </returns> private static List <int> CreateRandomNumbers (int maxNumber) {var array = new int [maxNumber]; for (var I = 0; I <maxNumber; I ++) {array [I] = I ;} var rnd = new Random (); for (var I = 0; I <maxNumber; I ++) {var index = rnd. next (0, maxNumber); if (I! = Index) {var tmpval = array [I]; array [I] = array [index]; array [index] = tmpval ;}} var list = new List <int> (); for (var I = 0; I <maxNumber; I ++) {list. add (array [I]);} return list ;} /// <summary> /// generate a random index list /// </summary> /// <param name = "maxNumber"> </param> /// <returns> </returns> private static List <int> CreateRandomNumbers2 (int maxNumber) {List <int> list = new List <int> (); Random rd = New Random (); while (list. Count () <maxNumber) {int I = rd. Next (0, maxNumber); if (! List. contains (I) {list. add (I) ;}} return list ;} /// <summary> /// generate a random index list /// </summary> /// <param name = "maxNumber"> </param> /// <returns> </returns> private static List <int> CreateRandomNumbers2 (int maxNumber) {var array = new int [maxNumber, 2]; var index = maxNumber-1; var rnd = new Random (); while (index> 0) {array [index, 0] = index; array [index, 1] = rnd. next (0, maxNumber); index --;} var list = new List <int> (); for (var I = 0; I <maxNumber; I ++) {for (var j = I + 1; j <maxNumber; j ++) {if (array [I, 1]> array [j, 1]) {var tIndex = array [I, 0]; var tValue = array [I, 1]; array [I, 0] = array [j, 0]; array [I, 1] = array [j, 1]; array [j, 0] = tIndex; array [j, 1] = tValue ;}}for (var I = 0; I <maxNumber; I ++) {list. add (array [I, 0]);} return list ;}

  

The first is the fastest, the second is the second, and the third is the slowest.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.