Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a random permutation of an array?

Tags:

c

I've written this function in C and I want it to create a random permutation or a list of numbers from 1 to n. I'm having trouble getting it to have no repeating numbers. So if you have n = 4, i would like it to return a random array containing 1-4 each only once, for example: {1,3,4,2}

int* random(int n) 
{
    int* r = malloc(n * sizeof(int));
    // initial range of numbers
    for(int i=0;i<n;++i){
        r[i]=i+1;
    }
    // shuffle
    for (int i = 1; i <= n; ++i){
        int j = rand() % i;
        r[i] = r[j];
        r[j] = i;
  }
  return r;
}
like image 564
user2238015 Avatar asked Apr 12 '13 00:04

user2238015


1 Answers

Change your second for loop to:

for (int i = n-1; i >= 0; --i){
    //generate a random number [0, n-1]
    int j = rand() % (i+1);

    //swap the last element with element at random index
    int temp = r[i];
    r[i] = r[j];
    r[j] = temp;
}

This is a Fisher-Yates shuffling algorithm. I have heard using rand() % n doesn't distribute uniformly, you've been warned.

And if you want to generate unique permutations everytime, you can store the generated permutations, maybe in a Dictionary or Hashmap, and then lookup everytime you return. I don't think C has a built in one but there should be libraries available.

like image 69
vidit Avatar answered Nov 11 '22 13:11

vidit