随机函数不断得到相同的结果[重复]

Posted

技术标签:

【中文标题】随机函数不断得到相同的结果[重复]【英文标题】:Random function keeps on getting same result [duplicate] 【发布时间】:2015-06-04 14:28:07 【问题描述】:

我正在编写一个程序来随机模拟骑士的巡回演出。 (参见***了解其含义:http://en.wikipedia.org/wiki/Knight%27s_tour)首先,我创建了一个国际象棋对象,它基本上只是一个 8*8 数组,其中包含数字来指示马的位置。我创建了一个国际象棋对象并为骑士随机分配了一个位置。然后,我随机移动马,直到没有更多的合法移动,并返回执行的移动次数。

int runTour ()
   
    srand (time(NULL));

    Chess knight(rand()%8, rand()%8); //Initialize random chess object.
    knight.printBoard(); //Prints the board before moving
    int moveNumber = 0; //A number from 0 to 7 that dictates how the knight moves
    int counter = 0;

    while (moveNumber != -1) //A moveNumber of -1 means there is no more legal move
       
        moveNumber = knight.findRandMove(knight.getRow(), knight.getColumn()); //findRandMove is a function that returns a legal random move for the knight based on its position. It works perfectly.
        knight.move(moveNumber); //move is a function that moves the knight
        counter ++; 
    
    knight.printBoard(); // Returns board when move is exhausted 
    return counter; //Returns number of moves performed.

有趣的是,虽然它从一个运行到另一个运行完全随机运行,但它在同一运行中不断输出相同的内容。例如,这是 main() 函数:

int main()
    runTour();
    runTour();
    return 0;

并且在 BOTH runTour() 中它输出:(其中 0 代表未到达的位置,1 代表骑士的当前位置,到达 9 个位置)

0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 

0 0 0 0 9 0 0 0 
0 9 9 0 0 0 9 0
0 0 0 0 0 9 9 0
9 0 9 9 9 9 0 1 
0 0 9 9 9 9 9 9
0 9 9 9 9 0 9 0
9 0 0 0 9 9 9 9
0 0 9 0 9 9 0 9 

当我再次运行它时,两个 runTour 输出:

0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 9 9
0 9 0 0 9 9 9 0
0 0 9 9 9 9 9 9
1 0 9 0 9 9 0 9 

所以随机函数在不同的运行中是随机的,但在每次运行中都是相同的。为什么会这样?如何修改代码,让 runTour() 在调用时有不同的表现?非常感谢您阅读这个笨拙的问题。

【问题讨论】:

【参考方案1】:

当您使用时间戳作为 srand 种子时: 如果两个 runTours 都在同一秒内,您认为您的代码会发生什么? ...srand 应该被准确地调用一次 次,而不是每次runTour 函数调用一次

【讨论】:

谢谢。在查看***.com/questions/7343833/srand-why-call-it-only-once@ 帖子后,我了解了 srand() 的问题【参考方案2】:

尝试将 srand 调用移至 main 函数。您应该只需要为生成器播种一次,而不是每次调用该函数。

【讨论】:

以上是关于随机函数不断得到相同的结果[重复]的主要内容,如果未能解决你的问题,请参考以下文章

RND函数怎么用

excel如何随机生成不重复整数?

随机函数RND使用

javascript生成随机字符[重复]

rand产生随机数怎样控制在1~52内而且不能重复。1~52必须出现一次。谢谢

随机变量以及近似函数的四种收敛形式