C语言中的Fisher Yates改组算法

Lor*_*chi 1 c

我被要求分配一个在数组上使用FisherYates shuffle的功能,以便使用函数从文件中提取(我设法做到)。

 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;
}
Run Code Online (Sandbox Code Playgroud)

从根本上讲,它只需要洗牌手列表,然后将输出返回给我,这样我就可以在main()中将其打印出来。

如果有人可以向我展示如何修改代码以使其正常工作,我将不胜感激,因为使用此版本,在编译时会出现错误:

 invalid conversion from 'int*' to 'int' [-fpermissive]
Run Code Online (Sandbox Code Playgroud)

Tec*_*ndz 5

您已经有了中的结果player,因此返回void应该可以。

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;
     }
}
Run Code Online (Sandbox Code Playgroud)

  • @Tectrendz我认为这是一个错字(因为你自己的链接说它是“%(i + 1)”),所以我决定编辑它。 (2认同)