c++ - Random function keeps on getting same result -


this question has answer here:

i writing program simulate knight's tour randomly. (see wikipedia means: http://en.wikipedia.org/wiki/knight%27s_tour) first, create chess object, 8*8 array numbers indicate position of knight. create chess object , randomly assign position knight. then, moved knight randomly until there no more legal moves , returns number of moves performed.

int runtour () {        srand (time(null));      chess knight(rand()%8, rand()%8); //initialize random chess object.     knight.printboard(); //prints board before moving     int movenumber = 0; //a number 0 7 dictates how knight moves     int counter = 0;      while (movenumber != -1) //a movenumber of -1 means there no more legal move     {            movenumber = knight.findrandmove(knight.getrow(), knight.getcolumn()); //findrandmove function returns legal random move knight based on position. works perfectly.         knight.move(movenumber); //move function moves knight         counter ++;      }     knight.printboard(); // returns board when move exhausted      return counter; //returns number of moves performed. 

}

the interesting thing while runs randomly run run, keeps outputting same thing in same run. example, main() function:

int main(){     runtour();     runtour();     return 0; } 

and in both runtour() outputs: (where 0 represents positions not reached, 1 represents current position of knight, , 9 positions reached)

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  

and when run again, both runtour output:

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  

so random function random in different runs, same in each run. why case? how can modify code runtour() can have different performances when called? thank reading clumsy question.

as you´re using timestamp srand seed:
if both runtours in same second, think happen code?
...
srand supposed called one time, not 1 time per function call of runtour


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -