lundi 21 décembre 2020

Is there a cleaner way to write this C code?

I have to fill a matrix with random numbers 0 or 1, but if a cell contains 1, the other 8 around it must be 0. 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;
        }
    }
}

Of course, I'm sure there is a cleaner way to write this code. Can you help me? Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire