Fisher Yates在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; } 

它基本上只需要随机播放播放器列表并将输出返回给我,这样我就可以在main()中打印出来。

如果有人能告诉我如何修改代码以使其工作,我将非常感激,因为在这个版本中,我在编译时遇到错误:

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

你已经在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; } } 

关于你的function的两个快速事项:

1) rand()要求调用srand(…)来为数字生成器设定种子。

  ... 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)是原型返回一个int ,但是你返回pointer to intpointer to int这三个选项是按照Tectrendz建议做的,只是改变原型返回void (因为player在参数),或更改函数以返回int * 。 但这是多余的,因为它已经存在于论证中。