title: How to create a random permutation of an array?
body: <p>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}</p>
  
  <pre><code>int* random(int n) 
  {
      int* r = malloc(n * sizeof(int));
      // initial range of numbers
      for(int i=0;i&lt;n;++i){
          r[i]=i+1;
      }
      // shuffle
      for (int i = 1; i &lt;= n; ++i){
          int j = rand() % i;
          r[i] = r[j];
          r[j] = i;
    }
    return r;
  }
  </code></pre>