[英]How to fill the Array with the rand Function?
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. 此后,我必须为位置提供rand()函数,停止条件是查找邻居分配的值1的位置。 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处于位置0或(size-1)时才为a。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.