如果我有一个位置或行/列同时用于 A 和 B 位置,请检查 B 是否与 A 成对角线?
1 2 3
4 5 6
7 8 9
例如,我如何检查 5 是否与 7 成对角线?
此外,如果我检查 4 是否是对角线 3,它不应该也得到真正的返回吗?
下面的回答结合了我的情况。
我从另一个函数调用它
!isDiagonal(goodguyposition, positionadd1)
public static boolean isDiagonal(int a, int b)
{
// x = number of columns
// y = number of rows
// s = index start (1)
// a = index of a
// b = index of b
int x = 11;
//int y = 11;
int s = 0;
int ax = (s - a) % x, ay = (s - a) / x, bx = (s - b) % x, by = (s - b) / x;
if ((ax == bx - 1 || ax == bx + 1) && (ay == by - 1 || ay == by + 1))
{
trả về giá trị đúng;
}
khác
{
trả về false;
}
}
为提高可读性而清理的响应:
public static boolean isAdjacentDiagonal(int x, int s, int a, int b) {
// x = number of columns
// s = index start
// a = index of a
// b = index of b
int ax = (a - s) % x, ay = (a - s) / x, bx = (b - s) % x, by = (b - s) / x;
return (bx == ax - 1 || bx == ax + 1) && (by == ay - 1 || by == ay + 1);
}
使用 Math.abs 且仅当您的索引从 0 开始时:
public static boolean isAdjacentDiagonal(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
return Math.abs(ax - bx) == 1 && Math.abs(ay - by) == 1;
}
public static boolean isOneOfDiagonals(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
return a != b && Math.abs(ax - bx) == Math.abs(ay - by);
}
Tôi là một lập trình viên xuất sắc, rất giỏi!