Skip to content
Advertisement

What is the quickest way to determine if two elements are in the same row or column in a 2D array?

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?

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?

Advertisement

Answer

Here’s one approach for rows.

int[][] v = {{1, 2}, {3, 4}, {5, 6}};
System.out.println(rowContains(v, 2, 3));
System.out.println(rowContains(v, 5, 6));

Prints

false
true

The method

  • stream single d array and ignore duplicates
  • count filter on finding the values.
  • return true if any final count is 2.
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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement