Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fisher Yates shuffling algorithm in C

Tags:

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]
like image 485
Lorenzo Battilocchi Avatar asked Mar 13 '26 23:03

Lorenzo Battilocchi


1 Answers

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;
     }
}
like image 106
Tectrendz Avatar answered Mar 15 '26 22:03

Tectrendz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!