I want to fill a matrix starting from the center. After this, I must supply positions with the rand () function, the stop condition being to find a position where the neighbor has a value of 1 allocated. This must be done until you reach the boundary of the matrix, that is, a for x or y when they assume position 0 or (size-1)
x = y = (size + 1) / 2;
matrix[x][y]=1; //default of the matrix
do{
x1=rand() %(size-1); //random position in x
y1=rand() %(size-1); // random position in y
matrix[x1][y1]=1; //declare the value in the position obtained
}while((matrix[x1-1][y1 ]==0)||
(matrix[x1+1][y1 ]==0)||
(matrix[x1 ][y1-1]==0)||
(matrix[x1 ][y1+1]==0)||
(x1==x)||(y1==y));
My main question is whether my conditional is true, and how could I stop this bond when I reach the boundary of the matrix.
To move outward from the center of the matrix, select a square around the center and iterate through the elements in that square. Here is an example which works with a matrix with an odd size. You can add additional conditions for setting the value based on the value of the neighbors.
int main(void)
{
srand((unsigned)time(NULL));
int size = 21;
int **matrix = malloc(size * sizeof(int*));
for(int i = 0; i < size; i++)
matrix[i] = malloc(size * sizeof(int));
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
matrix[i][j] = 0;
int center = size / 2 + 1;
matrix[center][center] = 1;
for(int range = 1; range < size / 2; range++)
{
for(int i = center - range; i < center + range; i++)
for(int j = center - range; j < center + range; j++)
{
if(
(i == (center - range))||
(j == (center - range))||
(i == (center + range - 1))||
(j == (center + range - 1))
)
if(rand() % 2)
matrix[i][j] = 1;
}
}
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
printf("%d", matrix[i][j]);
printf("\n");
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.