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, after having checked it contains 0 and the distance between this cell and other cells containing 1 is >= 1. All this is done until the number m entered by the user becomes 0.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void initialize(int n, int a[n][n]);
void createMap(int n, int a[n][n], int m);
int check (int i, int j, int v, int w);
void print(int n, int a[n][n]);
int main(){
int n;
printf("Insert square matrix size: ");
scanf("%d", &n);
int m;
printf("Insert 1s number: ");
scanf("%d", &m);
int a[n][n];
initialize(n,a);
createMap(n,a,m);
}
//Filling the matrix with 0
void initialize(int n, int a[n][n]){
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
a[i][j] = 0;
}
}
}
//Setting in random position 1 value
void createMap(int n, int a[n][n], int m){
int x1; int x2;
int b[0][0];
while (m > 0){
int i = rand() % n;
int j = rand() % n;
if (a[i][j] == 0 && (check(i,j,x1,x2) == 1)){
a[i][j] = 1;
m--;
//I have to fill b array with coordinates and then to pass
//b array to check function to do the check in the whole b array
}
}
print(n,a);
}
//checking if I can set the value to 1
int check (int x1, int y1, int x2, int y2){
if (sqrt(pow((x1-x2),2) + pow((y1-y2),2)) >= 1){
return 1;
} else {
return 0;
}
}
//Printing the matrix
void print(int n, int a[n][n]){
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
printf("\t%d",a[i][j]);
}
puts("");
}
}