# 最佳方法检查数组中两个元素是否在对角线上。

go评论57阅读模式

Best way to check if two elements of an array of array are in diagonal

# 问题

``````_________________
|   | * |   |   |
-----------------
|   |   |   |   |
-----------------
|   |   |   | * |
-----------------
|   |   |   |   |
-----------------
``````

I have indexes of two elements of an array of array (not of primitive objects) :
first element = tab[x0][y0]
second element = tab[x1][y1]

And i want to check if both of these elements are in diagonal like :

``````_________________
|   | * |   |   |
-----------------
|   |   |   |   |
-----------------
|   |   |   | * |
-----------------
|   |   |   |   |
-----------------
``````

Here both of these points are in diagonal, so we should return true.
But what is the best way to check it ?

# 答案1

``````    int rise = y1 - y0;
int run = x1 - x0;
``````

``````    if (Math.abs(rise) == Math.abs(run)) {
if (Integer.signum(rise) == Integer.signum(run)) {
// 对角线
} else {
// 另一个方向的对角线
}
} else {
// 非对角线
}
``````

Treat the array like a Cartesian coordinate space, and calculate the slope (rise over run) of the line joining the two elements (points):

``````int rise = y1 - y0;
int run = x1 - x0;
``````

If `rise` divided by `run` is 1 or -1, then the two elements form a diagonal. 1 or -1 determines the direction of the diagonal. Rather than dividing, you can just check if they have the same sign and magnitude:

``````if (Math.abs(rise) == Math.abs(run)) {
if (Integer.signum(rise) == Integer.signum(run)) {
// diagonal
} else {
// diagonal that is another direction
}
} else {
// not diagonal
}
``````

# 答案2

``````x0 - x1 == y0 - y1
``````

Two points are diagonal if the difference between the x coordinates and the y coordinates is the same.

``````x0 - x1 == y0 - y1
``````

# 答案3

``````boolean is_diagonal = (x1 - x0) == (y1 - y0);
``````

Just look at the coordinates. Being on a diagonal means that the differences in the `x` coordinate and in the `y` coordinate are the same. Thus:

``````boolean is_diagonal = (x1 - x0) == (y1 - y0);
``````

# 答案4

``````int x = x0 - x1 = 2
int y = y0 - y1 = 2

boolean diagonal = x == y;
``````

diagonal if

``````int x = x0 - x1 = 2
int y = y0 - y1 = 2

boolean diagonal = x == y;
``````

any other combination of index will to give you an equation which means they are not diagonal. also probably you will have to use Math.abs()

• 本文由 发表于 2020年10月2日 17:30:50
• 转载请务必保留本文链接：https://go.coder-hub.com/64169278.html
• java

go 52

go 72

go 62

go 56