确定2D数组中的两个元素是否在同一行或同一列中的最快方法是什么? [英] What is the quickest way to determine if two elements are in the same row or column in a 2D array?
问题描述
作为我的程序之一,我试图检查2D数组中的两个元素是否在同一行或同一列中.我知道可能有很多方法可以解决这个问题,主要是通过循环和遍历数组,但是我只是想知道:有没有一种快速的方法来确定这一点?
As part of one of my programs, I'm trying to check if two elements in a 2D array are part of the same row or column. I know there might be many ways to go about this, mainly with loops and by iterating through the array, but I was just wondering: is there any quick way to determine this?
假设我有一个二维数组,看起来像 {{1,2},{3,4},{5,6}}
.有没有一种快速的方法来确定 1
和 2
属于同一行?几乎可以在if语句中将其评估为",如果项目 x
与项目 y
属于同一行,那么就这样"; ?如果没有,那么最快的方法是什么?
Let's say I have a 2D array that looks like {{1, 2}, {3, 4}, {5, 6}}
. Would there be any fast way to determine that 1
and 2
belong to the same row? Almost in a way that it could be evaluated in an if statement as "if item x
belongs to the same row as item y
, then do so and so"? If not, then what would be the quickest way otherwise?
推荐答案
这是一种行处理方法.
int[][] v = {{1, 2}, {3, 4}, {5, 6}};
System.out.println(rowContains(v, 2, 3));
System.out.println(rowContains(v, 5, 6));
打印
false
true
方法
- 流单个d数组,并忽略重复项
- 计数过滤器以查找值.
- 如果最终计数为2,则返回true.
public static boolean rowContains(int[][] v, int v1, int v2) {
return Arrays.stream(v)
.map(arrs -> Arrays.stream(arrs)
.distinct().filter(a -> a == v1 || a == v2)
.count()).anyMatch(a -> a == 2);
}
对于列,最简单的方法是编写一种方法以转置列和行并重新运行该方法.
For columns, the easiest way would be to write a method to transpose the columns and rows and re-run the method.
这篇关于确定2D数组中的两个元素是否在同一行或同一列中的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!