[英]Creating an N by N grid of letters so that no two adjacent letters are the same
我需要打印出一個N到N的網格,其中包含字母A到F,以便沒有兩個相鄰的字母相同。 下面的代碼打印出N x N的網格,但是我只能使左右的字母不同。 我找不到一種使上下字母不同的方法。 我需要在不使用數組的情況下解決此問題。 字母必須隨機。
public static void main(String[] args) {
int N = StdIn.readInt();
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);
}
if (c == 1) {
System.out.print("A ");
}
if (c == 2) {
System.out.print("B ");
}
if (c == 3) {
System.out.print("C ");
}
if (c == 4) {
System.out.print("D ");
}
if (c == 5) {
System.out.print("E ");
}
if (c == 6) {
System.out.print("F ");
}
x = c;
}
System.out.println();
}
我幫你簡化了for循環
for (int row = 0; row < N; row++) {
char c = (char) (Math.random() * 6 + 'A');
while (x == c) {
c = (char) (Math.random() * 6 + 'A');
}
System.out.print(c + " ");
x = c;
}
它使用字母的ASCII值,因此您不需要大的if語句。
您的問題尚不清楚允許使用哪種存儲格式,但是請考慮以下問題:如果您可以將每一行存儲為一個字符串(在移動一行后將刪除一個臨時字符串),那么如何檢查該行中的字母是否為在它下面重新構建與上面的字母匹配? 將字符串視為數組(這是其真實形式)。
輕松完成2個隊列。
如果您分析以下內容,您應該意識到您實際上只需要一個大小為N的鏈表。
current
是當前行,每個新元素都只是排隊。
last
是上一行。 完成一行后,它將獲取current
的值,然后我們要檢查的第一個元素在最前面。
我將第一行與其他行分開,以使事情更簡單和更容易理解。
int N = 10;
Queue<Character> last,
current = new Queue<Character>();
char prev = '0';
for (int row = 0; row < N; row++)
{
char c;
do { c = (char)(Math.random() * 6 + 'A'); }
while (prev == c);
current.enqueue(c);
prev = c;
System.out.print(c + " ");
}
System.out.println();
for (int col = 1; col < N; col++)
{
last = current;
current = new Queue<Character>();
prev = '0';
for (int row = 0; row < N; row++)
{
char c;
do { c = (char)(Math.random() * 6 + 'A'); }
while (last.peek() == c || prev == c);
current.enqueue(c);
last.dequeue();
prev = c;
System.out.print(c + " ");
}
System.out.println();
}
您可以使用一對堆棧和一個候選字符來執行此操作。 NxN網格由最多包含N個N個字符的堆棧表示。 嘗試使用一副紙牌,用兩張紙牌代表的疊紙堆來嘗試一下,以了解其工作原理。
基本上,您要繪制一張卡片,並最多檢查兩個項目。 因為保證堆棧A永遠不會有鄰接,所以一旦放置項目,就永遠不必將其刪除。 所以一旦結束,就完成了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.