c++randomdev-c++knights-tour

Random function keeps on getting same result


I am writing a program to simulate Knight's tour randomly. (See wikipedia for what it means: http://en.wikipedia.org/wiki/Knight%27s_tour) First, I create a chess object, which is basically just a 8*8 array with numbers to indicate the position of the knight. I create a chess object and randomly assign a position for the knight. Then, I moved the knight randomly until there is no more legal moves and returns the number of moves performed.

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.

}

The interesting thing is that while it runs perfectly randomly from run to run, it keeps outputting the same thing in the same run. For example, this is the main() function:

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

And in BOTH runTour() it outputs: (where 0 represents positions not reached, 1 represents the current position of the knight, and 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 I run it 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 the random function is random in different runs, but is the same in each run. Why is this the case? How can I modify the code so that runTour() can have different performances when it is called? Thank you very much for reading this clumsy question.


Solution

  • As you´re using a timestamp as srand seed:
    If both runTours are in the same second, what do you think will happen with your code?
    ...
    srand is supposed to be called exactly one time, not one time per function call of runTour