【问题标题】:Fisher Yates shuffling algorithm in CC中的Fisher Yates洗牌算法
【发布时间】:2017-07-08 08:43:15
【问题描述】:

有人要求我分配一项使用 FisherYates 洗牌的任务,该数组使用函数从文件中获取(我设法做到了)。

 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]

【问题讨论】:

  • 要获得帮助,您必须描述您的代码有什么问题。例如,您“在编译时遇到了很多错误”,但您没有描述这些错误是什么或您尝试如何修复它们。看起来你的算法也是错误的:你想选择一个介于 0 和 i(包括)之间的随机数来交换元素 i,但你的随机数在 0...RAND_MAX 范围内。你也不需要道歉和解释自己——一个写得很好的问题就足够了。 stackoverflow.com/tour 是一本关于如何使用该网站的好书。
  • 错误出现在哪一行?另外,你可能不想返回player:它已经改变了,因为它是一个指针,不需要返回它。
  • @Evert 实际上,这可能是错误的根源,因为player 不是int,而是int*
  • 你会想要限制随机值的范围。它必须是您的数组的有效索引。
  • @pjs 这也是我的怀疑,在这种情况下,错误发生在其他地方,因此我对这条线提出了疑问。因此,目前的问题没有足够的信息。

标签: c


【解决方案1】:

您已经在player 中获得了结果,因此返回void 应该可以。

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;
     }
}

【讨论】:

  • rand() % n 不正确 -- rand() % (i + 1) 是。您的代码会产生随机随机播放,但不会产生均匀分布的随机播放(即使您假设 rand 是一个很好的随机数生成器)。
  • @PaulHankin:你介意为我们不那么精明的随机程序员扩展你的评论吗?
  • @chqrlie 因为算法是这样工作的?关键是a[i]a[0..i] 交换(因此不可能交换),而不是a[0..n-1]
  • @chqrlie 维基百科解释:en.wikipedia.org/wiki/…en.wikipedia.org/wiki/…
  • @Tectrendz 我认为这是一个错字(因为你自己的链接说它是% (i + 1)),所以我决定编辑它。
【解决方案2】:

关于你的函数的两件事:

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 int参数),更改函数以返回int *。但这将是多余的,因为它已经在参数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 2023-03-27
    • 2011-01-28
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多