#Help with a Conway function

2 messages · Page 1 of 1 (latest)

coral fiber
#

Hello, I have been working on implementing a simple conways game of life for a TUI and I just wanted to get some feedback on suggestions on one of the main functions. My understanding of C/C++ is still pretty shallow, but it works at the moment. I have added some comments for things I have some questions about, but I would appreciate any general advice.

// board is just a reference to an array that holds the "map"
typedef nc::NdArray<bool>* board;

// this function takes a pointer to a board, and then changes the underlying map to a new one (according the conway's game of life rules)
void step_board(board old_arr_ptr) {
    auto old_arr = *old_arr_ptr;
    
    auto old_arr_rows = old_arr.numRows();
    auto old_arr_cols = old_arr.numCols();

    auto ncarray = nc::zeros<bool>(old_arr_rows, old_arr_cols);

    for (auto row = 0; row < old_arr_rows; ++row)
    {
        for (auto col = 0; col < old_arr_cols; ++col)
        {
            // These are the slices that determine who the neighbours are 
            auto row_w = nc::Slice(std::max(row - 1, 0), std::min(row + 2, (int)old_arr_rows));
            auto col_w = nc::Slice(std::max(col - 1, 0), std::min(col + 2, (int)old_arr_cols));
            
            // This part is one that maybe I am most unsure about... It is NumCPP specific, but initially I thought I could have this:
            // auto neighbours = (old_arr(row_w, col_w).sum() - (int)old_arr(row, col)).item();    Without "astype<int>", but it doesn't
            // actually sum the booleans it seems, so then I am forced to make a copy using `astype`... I need to see if I can find a way that I don't have to copy
            // array every single iteration
            auto neighbours = (old_arr(row_w, col_w).astype<int>().sum() - (int)old_arr(row, col)).item();
            
            bool alive = old_arr(row, col);

            if (alive)
            {
                if (neighbours == 2 || neighbours == 3)
                {
                    ncarray(row, col) = true;
                }
            }
            else
            {
                if (neighbours == 3)
                {
                    ncarray(row, col) = true;
                }
            }
        }
    }

    // This is something I still need to search more, as in why does the bellow work, but this:
    // old_arr = ncarray; doesn't?
    (*old_arr_ptr) = ncarray;
}
vale echoBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.