Fisher Yates shuffling algorithm in C

Posted on

Fisher Yates shuffling algorithm in C

I have been asked for an assignment to use FisherYates shuffle on an array to be taken in from a file (that, I managed to do) using functions.

 int FisherYates(int *player, int n) { //implementation of Fisher                 
     int i, j, tmp; // create local variables to hold values for shuffle

     for (i = n - 1; i > 0; i--) { // for loop to shuffle
         j = rand(); //randomise j for shuffle with Fisher Yates
         tmp = player[j];
         player[j] = player[i];
         player[i] = tmp;
     }
     return player;
}

It basically just needs to shuffle the list of players and return me the output so I can print it out in main().

I would very much appreciate it if anyone could show me how to modify the code to make it work, since with this version, I get a error at compile time:

 invalid conversion from 'int*' to 'int' [-fpermissive]

You already have the result in player, so returning void should work.

Reference for Fisher-Yates

void FisherYates(int *player, int n) { //implementation of Fisher
     int i, j, tmp; // create local variables to hold values for shuffle

     for (i = n - 1; i > 0; i--) { // for loop to shuffle
         j = rand() % (i + 1); //randomise j for shuffle with Fisher Yates
         tmp = player[j];
         player[j] = player[i];
         player[i] = tmp;
     }
}

Two quick things about your function:

1) rand() requires that srand(…) be called to seed the number generator.

 ...
 srand(clock());

 for (i=n-1; i>0; i--){ // for loop to shuffle
     j = rand()%n; //randomise j for shuffle with Fisher Yates
     ...

2) int FisherYates(int *player, int n) is prototyped to return an int, but you are returning pointer to int Options are to do as Tectrendz suggested and just change the prototype to return void (since player is returned in the arguments), or change the function to return an int *. But this would be redundant because it is already in the arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *