我必须在 10X10 网格阵列中打印随机游走(字母 A-Z),向任一方向移动 只要移动不退出数组并且不与现有字母重叠即可。
我的输出是一个完整的“.”网格没有字母,保留 A 来标记开始。
我看到了解决方案,并且关于条件测试和案例,我认为与我自己的没有什么区别。
我尝试注释掉测试并检查循环是否放置了随机方向数并且 下一个字母正确,它确实如此。然而问题似乎出在测试上,但我坚持 答案(至少在外观上)与我的没有不同。
这是我的程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
char t[10][10] = {0}, c;
int i, j, dir;
srand((unsigned) time(NULL));
t[0][0] = 'A';
for (c='B'; c <= 'Z'; c++) {
dir = rand() % 4;
// printf("%c\t%d\n\n", c, dir); // Here proves to be correct if tests are omitted
if (dir == 0 && i+1 < 10 && t[i+1][j] == '.')
t[++i][j] = c;
else if (dir == 1 && j+1 < 10 && t[i][j+1] == '.')
t[i][++j] = c;
else if (dir == 2 && i-1 >= 0 && t[i-1][j] == '.')
t[--i][j] = c;
else if (dir == 3 && j-1 >= 0 && t[i][j-1] == '.')
t[i][--j] = c;
else
break;
}
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
if (t[i][j] == 0)
t[i][j] = '.';
printf("%c ", t[i][j]);
}
printf("\n");
}
return 0;
}
i
和 j
初始化为 0
。0
进行比较,而不是 '.'
。这是我的版本:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
char t[10][10] = {0};
int i = 0, j = 0, dir;
srand((unsigned) time(NULL));
t[i][j] = 'A';
for (char c = 'B'; c <= 'Z'; c++) {
dir = rand() % 4;
if (dir == 0 && i+1 < 10 && !t[i+1][j])
t[++i][j] = c;
else if (dir == 1 && j+1 < 10 && !t[i][j+1])
t[i][++j] = c;
else if (dir == 2 && i-1 >= 0 && !t[i-1][j])
t[--i][j] = c;
else if (dir == 3 && j-1 >= 0 && !t[i][j-1])
t[i][--j] = c;
}
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++)
printf("%c ", t[i][j]);
printf("\n");
}
return 0;
}
这是它的三个执行:
[gmt@arch ~]$ ./a.out
A B X V
F G I T U
J M Q R S
O P
[gmt@arch ~]$ ./a.out
A
E F
M G H
L J I
[gmt@arch ~]$ ./a.out
A
C D
F E
H
I
J P
Q R
S T V Y Z
W X
这里...
char t[10][10] = {0}, c;
...您将
t
的所有元素初始化为 0。
这里...
if (dir == 0 && i+1 < 10 && t[i+1][j] == '.')
t[++i][j] = c;
else if (dir == 1 && j+1 < 10 && t[i][j+1] == '.')
t[i][++j] = c;
else if (dir == 2 && i-1 >= 0 && t[i-1][j] == '.')
t[--i][j] = c;
else if (dir == 3 && j-1 >= 0 && t[i][j-1] == '.')
t[i][--j] = c;
else
break;
...,虽然
t
中除 [0][0]
之外的所有元素仍为 0,但只有当目标单元格包含值 '.'
(即 not 0)时,您才采取一步。因此,您将永远不要迈出一步。
此外,您显然假设
i
和 j
最初包含 0 和 0,但它们没有初始化,因此它们的值实际上是不确定的。该程序可能会碰巧表现得好像它们最初为零,但它决不限于这样做。将它们初始化为 0,对应于初始位置。
另请注意,如果无法在随机选择的方向上采取步骤,则会跳出循环。也许这是必需的行为,但由于您从角落开始,这意味着 50% 的时间您根本不会采取任何步骤,另外 25% 的时间您只会采取一步。也许你应该从中间的某个地方开始?或者只有当没有没有可以采取步骤的方向时才跳出循环?