0
所以我给我设置了以下问题:编写一个采用整数命令行参数N的程序,并使用两个嵌套的for循环打印N-N在6个颜色之间交替出现的棋盘,这些颜色随机分隔。颜色用字母表示(如'r'表示红色,'b'表示蓝色)。彼此旁边不允许有两个相同的颜色。创建一个所有相邻颜色不同的随机颜色网格
所以,我知道我可能需要数组来解决这个问题。我尝试了几种方法,都出现了错误。以下是我最近的尝试之一,但我不确定如何通过网格并进行更正。代码的作用是使每一行随机化,没有左右颜色相同,但列不固定。
请注意,我是第一年没有编程历史的CS学生。我猜,要解决这个问题,心不是太复杂了,但是,我不能看到一个简单的解决方案...
int N = StdIn.readInt();
int array1[] = new int[N];
for (int column = 0; column < N; column++) {
int x = 0;
for (int row = 0; row < N; row++) {
int c = (int) (Math.random() * 6 + 1);
while (x == c) {
c = (int) (Math.random() * 6 + 1);
array1[row] = c;
}
if (c == 1) {
System.out.print("R ");
}
if (c == 2) {
System.out.print("O ");
}
if (c == 3) {
System.out.print("Y ");
}
if (c == 4) {
System.out.print("G ");
}
if (c == 5) {
System.out.print("B ");
}
if (c == 6) {
System.out.print("I ");
}
x = c;
}
System.out.println();
}
}
我刚刚测试了你的代码。它的工作正常。我输入5,我得到了你提到的所有不同颜色的5x5网格。 – Smit 2013-03-27 17:23:50
不允许相邻的颜色相同。 – Steve 2013-03-27 17:31:57
你的意思是明智的行或明智的列?我根本没有看到任何相邻的行,但我确实看到明智的列。 – Smit 2013-03-27 17:56:07