Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I speed up this function? [closed]

I'm trying to write John Conway's Game of Life in C, but I'm having trouble adding living cells to the board. The function I wrote to handle it is extremely slow.

Thought process: I want to add n living cells to the board randomly, so while cells left to set alive, get a random (x, y) pair, and if it's dead, make it living. That way I can guarantee n cells become alive.

Is my understanding of the problem incorrect, or am I just being inefficient? Why is it so slow, and how can I make it faster?

void add_cells( int board[BOARD_WIDTH][BOARD_HEIGHT], int n )
{
    //  Randomly set n dead cells to live state.
    while ( n )
    {
        int randX = rand() % BOARD_WIDTH;
        int randY = rand() % BOARD_HEIGHT;

        if( board[randX][randY] == 0 )
        {
            board[randX][randY] = 1;
            n--;
        }
    }
}
like image 710
MaxG Avatar asked Apr 29 '26 22:04

MaxG


1 Answers

If let's say 70% of cells are alive, then it means that your program will have to find an other cell 7 times out of 10, which makes unecessary repetitions.

You could pop the selected cell out from a "remaining cells" array when you set it alive, and select your cell randomly in this array. I suggest to use a dynamicaly resizable container so you don't have to manipulate your entire "remaining cells" array each time you pop out a cell. This should help save you more time.

like image 146
V. Brunelle Avatar answered May 01 '26 14:05

V. Brunelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!