Algorithm-random non-repeating sequence generation

Source: Internet
Author: User

At work today, it is easy to see the topic on the net, the topic is this: given a positive integer n, you need to output an array of length n, the array element is a random number, the range is 0–n-1, and the element cannot be duplicated. For example, n = 3 o'clock, you need to get an array of length 3, the element range is 0-2, the simple understanding is to generate an unordered random array, on the road to think about a bit back in three ways to achieve a bit; OC realized a bit, the end of the article by the way C # is the implementation method;

forever while.

While basically learning the language of the beginning of the process branch statement will involve while, if there is always random, does not exist to jump out of judgment, generally the first thought is this method:

+ (Nsarray *) Getresultone: (nsinteger) count{    nsmutablearray *arr=[nsmutablearray array];    for (Nsinteger i=0; i<count; i++) {        Nsinteger number=arc4random ()%count;        If there is a random go down        while ([Arr containsobject:@ (number)]) {            number=arc4random ()%count;        }        [Arr addobject:@ (number)];    }    return arr;}

Call Mode:

    Nsarray *arr=nil;    Arr=[arrayrandom Getresultone:5];    for (Nsinteger i=0; I<[arr count]; i++) {        NSLog (@ "%@", [Arr[i]stringvalue]);    }
Array Filtering

The second way actually said to write code leaf encountered this situation, a bit similar to the ball from the box, put back and do not go back to this mode, if the box of each ball color is not the same is taken out to put back, then take the next must and before the color is not the same, the specific implementation:

+ (Nsarray *) Getresulttwo: (nsinteger) count{    nsmutablearray *originalarr=[nsmutablearray array];    Nsmutablearray *resultarr=[nsmutablearray array];    Generate an array in order for    (Nsinteger i=0; i<count; i++) {        [Originalarr addobject:@ (i)];    }    Nsinteger Total=count;    for (Nsinteger i=0; i<count; i++) {        Nsinteger index=arc4random ()%total;        Random results are added to the result set        [Resultarr Addobject:originalarr[index]];        Delete the result from the original array        [Originalarr Removeobject:originalarr[index]];        total--;    }    return Resultarr;}
Exchange Method

The Exchange method means that you need to initialize an array, randomly generate the index, each time the value of the index position is placed in the head or tail, and then the next time the index will not go to the head and tail index, to give a simple example, assuming that the initialized array is 3,8,6,9, the random index range is 0-3, Assuming the first random random 2, the head Exchange is to change 3 and 6 a position, 6,8,3,9, the next time to take the index range is 1-3, the tail exchange is similar, C # version is the head Exchange, OC is the tail exchange, the principle is the same:

+ (Nsarray *) Getresultthird: (nsinteger) count{    nsmutablearray *originalarr=[nsmutablearray array];    Nsmutablearray *resultarr=[nsmutablearray array];    Generate an array in order for    (Nsinteger i=0; i<count; i++) {        [Originalarr addobject:@ (i)];    }    Nsinteger maxindex=count-1;    for (Nsinteger i=0; i<count; i++) {        nsinteger index=arc4random ()% (maxindex+1);        [Resultarr Addobject:originalarr[index]];        Assigns a randomly generated number to the lowest        Originalarr[index]=originalarr[maxindex];        Controls the value of the maximum index        maxindex--;    }    return Resultarr;}

At this time when I first write the code, carefully may find that the definition of two arrays, in fact, not necessary, one is enough, the following is the improved code:

+ (Nsarray *) Getresultfour: (nsinteger) count{    nsmutablearray *resultarr=[nsmutablearray array];    Generate an array in order for    (Nsinteger i=0; i<count; i++) {        [Resultarr addobject:@ (i)];    }    Nsinteger maxindex=count-1;    for (Nsinteger i=0; i<count; i++) {        nsinteger index=arc4random ()% (maxindex+1);        Random values and the bottom are exchanged        nsstring  *temp=resultarr[index];        Resultarr[index]=resultarr[maxindex];        Resultarr[maxindex]=temp;        Controls the value of the maximum index        maxindex--;    }    return Resultarr;}

Call the same way as before:

  Nsarray *arr=nil;    Arr=[arrayrandom Getresultthird:5];    for (Nsinteger i=0; I<[arr count]; i++) {        NSLog (@ "%@", [Arr[i]stringvalue]);    }        Nsarray *arr=nil;    Arr=[arrayrandom Getresultfour:5];    for (Nsinteger i=0; I<[arr count]; i++) {        NSLog (@ "%@", [Arr[i]stringvalue]);    }
C # version Code
 Class Program {static void Main (string[] args) {//Initialize an array if the array is not assigned, default is 0//int[]            arr = Solveproblemwayone (5);            int[] arr = Solveproblemwaysecond (5);            int[] arr = Solveproblemwaythird (10);            int[] arr = solveproblemwayfour (5); for (int i = 0; i < arr. Length; i++) {Console.Write (Arr[i].            ToString ());        } console.readkey (); }///<summary>///cycle to determine if the random numbers are in the array///</summary>//<param name= "Total"        ;</param>//<returns></returns> public static int[] Solveproblemwayone (int count)            {list<int> resultlist = new list<int> ();            Random random = new random (); for (int i = 0; i < count; i++) {int number = random.                Next (1, Count + 1);     while (Resultlist.contains (number)) {               Number = random.                Next (1, Count + 1);            } resultlist.add (number);        } return Resultlist.toarray (); }///<summary>///To generate an array in order///</summary>//<param name= "Total" ></p            aram>//<returns></returns> public static int[] Solveproblemwaysecond (int count) {            list<int> orignallist = new list<int> ();            list<int> resultlist = new list<int> ();            for (int i = 0; i < count; i++) {orignallist.add (i);            } int maxindex = count;            Random random = new random (); for (int i = 0; i < count; i++) {//random index int index = random.                Next (0, Maxindex);                Resultlist.add (Orignallist[index]);                Orignallist.removeat (index);            maxindex--; } RETurn Resultlist.toarray (); }///<summary>///Do not delete the data, then the problem is to assign the last thing///</summary>//<param name= "Count        "></param>///<returns></returns> public static int[] Solveproblemwaythird (int count)            {list<int> orignallist = new list<int> ();            list<int> resultlist = new list<int> ();            for (int i = 0; i < count; i++) {orignallist.add (i);            } int minindex = 0;            Random random = new random (); for (int i = 0; i < count; i++) {//random index int index = random.                Next (Minindex, Count);                Resultlist.add (Orignallist[index]);                Exchange, because of the index self-subtraction, do not need to assign a random value to the last//int temp = Orignallist[index];                Orignallist[index] = Orignallist[minindex];                Orignallist[minindex] = temp; minindex++;            } return Resultlist.toarray (); }///<summary>/////</summary>//<param name= "Count" &GT;&LT;/PARAM&G        T <returns></returns> public static int[] Solveproblemwayfour (int count) {list<            int> resultlist = new list<int> ();            for (int i = 0; i < count; i++) {resultlist.add (i);            } int minindex=0;            Random random = new random (); for (int i = 0; i < count; i++) {//random index int index = random.                Next (Minindex, Count);                Head Swap int temp = Resultlist[index];                Resultlist[index]=resultlist[minindex];                Resultlist[minindex] = temp;            minindex++;        } return Resultlist.toarray ();   }      }}

Algorithm-random non-repeating sequence generation

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.