jeudi 24 décembre 2020

Why a wrong number of 1 is printed?

My function should randomly insert a user-chosen number of 1 into my matrix. The difficulty lies in the fact that if a cell contains a 1 the cells around it must be set to 0. Why my code print a wrong number of 1? In the code below I had thought to first set the entire matrix to 0, then randomly generate a cell to be set to 1. Then, check if the cells around it are 0, otherwise set them to 0. All this is done until the number m entered by the user becomes 0 (every time a cell is set to 1, m is decremented and every time a cell equal to 1 is reset to 0 m it is incremented). Furthermore, in order not to generate errors, the check is done considering the fact that the outermost cells cannot check on nonexistent cells.This is my (bad) code. Can anyone tell me why the print is wrong?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int main (void) {
    int n, m;
    
    printf("Enter square matrix size: ");
    scanf("%d",&n);
    int matrix[n][n];
    
    printf("Enter number of 1 cells: ");
    scanf("%d",&m);
    
    int a[n][n];
    
    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            a[i][j] = 0;
        }
    }
      
            while (m >= 0){
                int k = rand() % n;
                int l = rand() % n;
                a[k][l] = 1;
                if (k > 0) {
                    if (a[k-1][l] == 1){
                        a[k-1][l] = 0;
                        m++;
                    }
                    if (l > 0 && a[k-1][l-1] == 1){
                        a[k-1][l-1] = 0;
                        m++;
                    }
                    if (l < 4 && a[k-1][l+1] == 1){
                        a[k-1][l+1] = 0;
                        m++;
                    }
                }
                
                if (k < 4){
                    if (a[k+1][l] == 1){
                        a[k+1][l] = 0;
                        m++;
                        if(l<4 && a[k+1][l+1] == 1){
                            a[k+1][l+1] = 0;
                            m++;
                        }
                    }
                } 
                
                if (l > 0 && a[k][l-1] == 1){
                    a[k][l-1] = 0;
                    m++;
                }
                
                if (l<4 && a[k][l+1] == 1){
                    a[k][l+1] = 0;
                    m++;
                }
                
                m--;
                }
                        
    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            printf("\t%d", a[i][j]);
        }
        puts("");
    }
    
    
    return 0;
}



Aucun commentaire:

Enregistrer un commentaire