cmatrixrandomcoding-stylecode-cleanup

Efficient and Elegant Solution for Filling a Matrix with 0s and 1s and Setting Surrounding Cells to 0 when Necessary


I need to fill a matrix with random 0s or 1s, but if a cell contains a 1, then all of the cells around it (8 cells in total) should be set to 0. I have attempted to implement this code, but I am unsure if there is a simpler way to do it. Can you please suggest a more efficient or elegant solution? Thank you!

As a beginner, I tried to implement my code in this way:

for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        a[i][j] = rand() % 2;
        if (a[i][j] == 1) {
            a[i-1][j-1] = 0; 
            a[i-1][j]   = 0; 
            a[i-1][j+1] = 0;
            a[i][j-1]   = 0; 
            a[i][j+1]   = 0;
            a[i+1][j+1] = 0; 
            a[i+1][j]   = 0; 
            a[i+1][j+1] = 0;
        }
    }
}

Solution

  • There is an easier way to do this: you need to use the Manhattan Formula. So, code can be:

    int distance = sqrt(pow((x1-x2),2) + pow((y1-y2),2))
    

    where x1, y1 are the coords of my cell and x2, y2 are the coords of the other cells containing 1. If distance < 1 you cannot set the cell to 1. So, you can create a matrix containing the coords of all cells containing 1 and do the check on the entire matrix before setting a cell to 1.