2

I have one int* array and I want to perform a random permutation to this array. The function is similar with randperm in MATLAB. For example, I have an array int* A=[0 1 1 0] and if I call randperm(A,sizeof A) then one possible output would be A=[1 0 0 1]

This is my function but there seems to be an error. Can anyone determine what this error is?

void randperm(int* permMatrix,int n)
{
    int i, j, t;
    for(i=0; i<n; i++) {
        j = rand()%(n-i)+i;
        t = permMatrix[j];
        permMatrix[j] = permMatrix[i];
        permMatrix[i] = t;
    }
    for(i=0; i<n; i++) {
        printf("%d ",permMatrix[i]);
    }
}
rayryeng
  • 102,964
  • 22
  • 184
  • 193
Jame
  • 3,746
  • 6
  • 52
  • 101

2 Answers2

6

It's always best to use standard library facilities where they exist. In this case, the <algorithm> header has a function std::random_shuffle() that does exactly what you want:

#include <algorithm>

void randperm(int* matrix, int size)
{
    std::random_shuffle(matrix, matrix + size);
}
Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82
0

Implementation of 'randperm' is correct but, may be sizeof(A) is not evaluated as 4. Please Check out value of 'n'.