lundi 13 février 2017

Is there a faster way to randomize a set of ordered numbers?

I made this game that's currently on the App Store called "Twinstones", and there is a "stone" selection Store page that allows you to choose what set of stones you'd like to play with (60 choices).

I wrote a randomizing function to make the stone options located in different column-row spots for different users. In terms of Big-O constraints, is my function considered linear on a logarithmic scale? Or is there, given an input of 10000 instead of 60, something that increases the time beyond reasonable means? I'm very new to this world of time-managed code, so bear with me:

#define STONES 60

- (void)randomizeStones {
    srand((unsigned int)time(NULL));

    char stone[STONES];
    char tester[STONES] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
                       21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,
                       39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,
                       57,58,59};


    int tracker = STONES;
    for (int i = 0; i < STONES; i++) {
        int r = rand() % tracker;
        stone[i] = tester[r];
        tester[r] = ' ';
        for (int j = r; j < tracker; j++) {
           tester[j] = tester[j+1];
           tester[j+1] = ' ';
        }
        tracker--;
    }
    // print out Stones order to verify (this function works just to throw that in there)
}

  1. Given the 60 number set, I get a random number of the current amount.
  2. That number gets "transferred" from the tester array to the first element of the stone array.
  3. Then, I remove that number from the index position in tester.
  4. The second for loop takes the values in the indexes greater than the chosen index and "moves" them one to the left in the tester array order.
  5. Then tracker is reduced by one to prevent the second for loop from constantly running 60 times around.

How efficient is this process (given that I want n Stones to be uniquely randomized without having to randomize on and on to find unique values)?




Aucun commentaire:

Enregistrer un commentaire