gpt4 book ai didi

java - 检查 5x6 矩阵中的相邻单元格

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:27:20 25 4
gpt4 key购买 nike

我有一个 5x6 矩阵,它是使用 Java Swing 中的各个按钮创建的。

我将它们命名为类似于棋盘,从左上到右下为 A1 到 F5。

现在,我想允许用户仅单击给定数量的相邻按钮,无论是水平还是垂直。

例如,值为 4。因此,用户必须只能选择矩阵中垂直或水平相邻的任意位置的 4 个按钮。

例如。 D2、C2、B2、A2(如果垂直选择)。或者,如果水平选择,可能是 D1、D2、D3、D4。

对于矩阵中的任何一组按钮实现此功能的算法方法是什么?

最佳答案

这是代码,我添加了一些注释以使其更清晰。

注意代码中的数组要排序

逻辑

水平

A1 => 01
A2 => 02
A3 => 03
A4 => 04

So A2 - A1 = 1

垂直

A1 => 01
B1 => 11
C1 => 21
D1 => 31

So B1 - A1 = 10

代码:

    public static void main(String[] args) {
String[] spots0 = { "A1", "B1", "C1", "D1" };
String[] spots1 = { "A1", "A2", "A3", "A4" };
String[] spots2 = { "A1", "B1", "B2", "B3" };

System.out.println(isCorrect(spots0) ? "correct" : "incorrect");
System.out.println(isCorrect(spots1) ? "correct" : "incorrect");
System.out.println(isCorrect(spots2) ? "correct" : "incorrect");
}

public static boolean isCorrect(String[] spots) {
int NONE = -1;
int HORIZONTAL = 1;
int VERTICAL = 2;

int pattern = NONE; //BY DEFAULT NONE

for (int i = 0; i < spots.length - 1; i++) {

//difference between 2 consecutive element in spots[]. If A2 - A1 = 1, and B1 - A1 = 10
int diff = toNum(spots[i + 1]) - toNum(spots[i]);

if (diff == 1) { // if HORIZONTAL
if (pattern == NONE) // if the first time
pattern = HORIZONTAL; // set pattern to vertical, this is used for later to check if any illigal change happen
else if (pattern == VERTICAL) { //if it was Vertical and changed, then error
return false;
}
} else if (diff == 10) { // if VERTICAL
if (pattern == NONE) // if the first time
pattern = VERTICAL; // set pattern to horizontal, this is used for later to check if any illigal change happen
else if (pattern == HORIZONTAL) { //if it was Horizontal and changed, then error
return false;
}

} else {
return false;
}
}
return true;
}

public static int toNum(String s) {
// A1 => 01 , B1 => 11, C2 => 22
return Integer.parseInt("" + ((int)s.charAt(0) - 'A') + s.charAt(1));
}

关于java - 检查 5x6 矩阵中的相邻单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23048216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com