Random Number Generator (rand) isn't Random?

I'm generating mazes, I can only pick the first or last column. And I can only choose an even row (if you start the row index at 1). I have the correct logic, except that the maze start position isn't random. If I generate 50 mazes, that are all 20x20, all starting positions will be the same. Any help will be appreciated. Thanks.

void Maze::generatePath()
    int startingColumn = -1;
    int startingRow = -1;

    srand (time(NULL));

    int side = rand() % 2;
    startingColumn = (width - 1) * side; // will get first or last column

    int row = rand() % height; // 0 -> height - 1

    if(row % 2 == 0) // even, add one, or subtract if last row
        if(row + 1 >= width)
            startingRow = row - 1;
            startingRow = row + 1;
        startingRow = row; // odd, keep it

    grid[startingRow][startingColumn] = ' '; // starting character is blank

I call this method every time I generate a new maze. This code is to get the starting position. I haven't written the rest.


Only call srand once when your program starts. By calling it over and over in the same second, you keep resetting the random number generator to the same state.

If you need better randomness you might use as random seed something better than time(NULL). It may be for example /dev/random(or more practically /dev/urandom) device on unix-like systems. For really hardcore cases some real radnomness based on physical phenomena might be desired. For instance this one: http://photonics.anu.edu.au/qoptics/Research/qrng.php

Need Your Help

Data Ownership between super class and sub class

java oop

When a subclass inherit a super class , what's the relationship between subclass and the fields with different accessibility defined in super class ,which field is owned by the subclass and which n...

What is relation between server side cookie and javascript cookie?

javascript http servlets

I want to know relation between cookies created by Cookie Class in Servlet and document.cookie in JS.