[英]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.