This code works in Java 7 without streams. The approach is the same using binarySearch
method. Ragged 2d arrays and an unlimited number of elements to search for are accepted.
And also with loops, this task is easier to solve with rows than with columns.
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5}, {6, 7, 8}};
System.out.println(sameRow(arr, 4, 5)); // true
System.out.println(sameCol(arr, 3, 8)); // true
System.out.println(sameCol(arr, 2, 5, 7)); // true
}
/**
* @param arr 2d array.
* @param elements 1d array of elements to search for.
* @return whether any column of a 2d array contains all elements from a 1d array.
*/
public static boolean sameCol(int[][] arr, int... elements) {
// iterate through the columns
for (int i = 0; ; i++) {
// take an array of values from the column, if any
int[] col = new int[arr.length];
// column counter
int j = 0;
// iterate through the rows
for (int[] row : arr)
// take those rows where this column is present
if (row.length > i)
// take the value from the column
// and increase the counter
col[j++] = row[i];
// until the columns are still present
if (j == 0) break;
// if this column contains all the search elements
if (containsAll(Arrays.copyOf(col, j), elements))
return true;
}
return false;
}
/**
* @param arr 2d array.
* @param elements 1d array of elements to search for.
* @return whether any row of a 2d array contains all elements from a 1d array.
*/
public static boolean sameRow(int[][] arr, int... elements) {
for (int[] row : arr)
if (containsAll(row, elements))
return true;
return false;
}
/**
* @param a first array.
* @param b second array.
* @return whether the first array contains all elements from the second array.
*/
public static boolean containsAll(int[] a, int[] b) {
for (int i : b)
if (Arrays.binarySearch(a, i) < 0)
return false;
return true;
}