我需要创建一个随机填充的数组,要考虑一个值1
可以遍历数组中位置的元素。从中间位置的值开始,然后为其他项选择随机位置,我希望它遍历数组,直到它在数组中找到值1
(看起来像分支)为止。我写了我想得到的代码,但是在请求了程序挂起的数组的尺寸之后,我什至认为这可能是由于while
条件造成的。有人可以帮我解决这个问题吗?谢谢!
#include <stdio.h>
#include <stdlib.h>
int **Alocar_matrix(int m, int n) { //function for allocation of memory
int i, **v;
//ponteiro para a matriz - pointer for matrix
v = (int **)calloc(m, sizeof(int *));
if (v == NULL) {
printf("Erro: Memoria Insuficiente"); //just a error test
return (NULL);
}
//alocacao das colunas da matriz
for (i = 0; i < m; i++) {
v[i] = (int*)calloc(n, sizeof(int));
if (v[i] == NULL) {
printf("Erro: Memoria Insuficiente");
return (NULL);
}
}
return (v); //retorna o ponteiro para a matriz
}
int main() {
int **matrix;
int i, j, x, y, step, erro, size;
erro = 0;
FILE *dla_program; //save the data in dla_program.txt
dla_program = fopen("dla.txt", "w");
do {
printf("Informe o tamanho da matriz quadrada desejada. Ela deve ser maior que 100!");
// it's a information from the user: the size of the matrix
scanf("%d", &size);
} while ((size < 100) || (size > 500));
if ((matrix = Alocar_matrix(size, size)) == NULL)
erro = 1;
if (erro) {
printf("\n Falta de memoria! Saindo...\n"); //erro na alocacao ---test of memory
exit(1);
}
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) //zerar a matrix -- define zero value to inicialization
matrix[i][j] = 0;
}
matrix[(size - 1) / 2][(size - 1) / 2] = 1; //particula localizada no centro ---allocation of memory
x = size + 1;
y = size + 1;
do {
while ((x >= size) || (y >= size)) { // while generalizado
while (1) {
x = rand() % size;
y = rand() % size;
if (matrix[x-1][y] || matrix[x+1][y] || matrix[x][y-1] || matrix[x][y+1] || matrix[x][y] == 0)
//escolher uma posição aleatória que não seja vizinha do centro -- a choice of random position
break;
}
if (rand() % 1 < 0.5)
step = 1; //condicional para definir a direção do deslocamento -- random movement
else
step = -1;
while (matrix[x-1][y] + matrix[x+1][y] + matrix[x][y-1] + matrix[x][y+1] == 0 || (x < size) || (y < size)) {
if (rand() % 1 < 0.5)
x += step;
else
y += step;
} //procurar um vizinho
matrix[x][y] = 1; //quando encontrar um vizinho dentro de "size" declara na posicao da matrix o valor 1
}
} while (matrix[size-1][y] || matrix[x][size-1] || matrix[0][y] || matrix[x][0] != 0);
for (i = 0; i < size; i++) {
printf("\n");
{
for (j = 0; j < size; j++)
fprintf(dla_program, "\t%d ", matrix[i][j]);
}
printf("Dados armazenados em dla.txt \n\n"); //data storage in dla.txt
fclose(dla_program);
}
}
答案 0 :(得分:1)
由于rand()返回此语句的整数
if (rand () % 1 < 0.5)
没有道理
尝试
if (rand() % 2 == 1)
获得50:50的机会。
答案 1 :(得分:0)
您的程序有多个问题:
rand() % 1
始终取值为0
,违反了随机化的目的。使用rand() % 2
或rand() & 1
获取随机二进制值。0
,所以不需要将矩阵初始化为calloc()
,这是一个好主意。fopen()
的返回值,以避免在文件创建失败时出现未定义的行为。scanf()
的返回值,以避免未定义的行为或在无效输入(例如来自空文件或具有非数字输入)上的无限循环。while(1)
嵌套循环会尝试将自由位置定位在所采取的位置附近,但是您访问矩阵中可能会超出范围或可能超出范围的偏移量,从而导致未定义的行为(系统上的分段错误)。您应该彻底简化该方法:
matrix[(size + 1) / 2][(size + 1) / 2]
,这是修改后的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// allocate an indirect matrix: an array of arrays of int
int **Alocar_matrix(int m, int n) {
int i, **v;
v = calloc(m, sizeof(*v));
if (v != NULL) {
for (i = 0; i < m; i++) {
v[i] = calloc(n, sizeof(*v[i]));
if (v[i] == NULL) {
// free the memory allocated so far and exit the loop
while (i-- > 0) {
free(v[i]);
}
free(v);
v = NULL;
break;
}
}
}
if (v == NULL) {
printf("Erro: Memoria Insuficiente");
}
return v;
}
int main() {
int **matrix;
int c, i, j, x, y, n, size, input_ok;
FILE *dla_program; //save the data in dla_program.txt
// choose a random seed
srand(clock());
dla_program = fopen("dla.txt", "w");
if (dla_program == NULL) {
printf("Cannot open output file dla.txt\n");
return 1;
}
size = 100;
input_ok = 0;
while (!input_ok) {
// get the matrix size from the user
printf("Informe o tamanho da matriz quadrada desejada. Ela deve ser maior que 100! ");
switch (scanf("%d", &size)) {
case 1:
if (size >= 100 && size <= 500) {
input_ok = 1;
break;
}
printf("invalid matrix size: %d\n", size);
break;
case 0:
printf("invalid input\n");
// consume pending input
while ((c = getchar()) != EOF && c != '\n')
continue;
break;
default:
printf("unexpected end of file\n");
return 1;
}
}
if ((matrix = Alocar_matrix(size, size)) == NULL) {
//erro na alocacao --- allocation failure
printf("\n Falta de memoria! Saindo...\n");
exit(1);
}
//particula localizada no centro --- start from the center
x = y = (size + 1) / 2;
for (;;) {
matrix[x][y] = 1;
// count the number of free neighbours
n = 0;
if (x > 0 && matrix[x - 1][y] == 0)
n++;
if (x < size && matrix[x + 1][y] == 0)
n++;
if (y > 0 && matrix[x][y - 1] == 0)
n++;
if (y < size && matrix[x][y + 1] == 0)
n++;
if (n == 0) {
// dead end
break;
}
// choose a random direction
n = rand() % n;
if (x > 0 && matrix[x - 1][y] == 0 && n-- == 0)
x--;
else if (x < size && matrix[x + 1][y] == 0 && n-- == 0)
x++;
else if (y > 0 && matrix[x][y - 1] == 0 && n-- == 0)
y--;
else
y++;
}
// display to the terminal
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++)
putchar(" X"[matrix[i][j]]);
printf("\n");
}
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++)
fprintf(dla_program, "\t%d", matrix[i][j]);
printf("\n");
}
printf("Dados armazenados em dla.txt \n\n"); //data storage in dla.txt
fclose(dla_program);
for (i = 0; i < size; i++)
free(matrix[i]);
free(matrix);
return 0;
}