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