Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two matrices have an identical row?

I'm trying to develop an algorithm in Java, which, given two matrices (let's say a and b), returns true if at least one row is identical in a and b.

Here's my attempt of method:

public static boolean check_row(int a[][], int b[][]){
        boolean check = false;
        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < b[0].length; j++){
                if(a[i][j] == b[i][j])
                    check = true;
            }
        }
        return check;
    }

And here's a simple main:

public static void main(String[] args){
        int a[][] = {{1,2}, {3,4}};
        int b[][] = {{1,2}, {7,8}};
        System.out.println(check_row(a, b));
    }

Here I get true because first row of both matrices is the same. But if I change the matrices initialization to this:

int a[][] = {{1,2}, {3,4}};
int b[][] = {{5,6}, {1,2}};

I get false, even though the first row of a and the second row of b are identical.

How should I modify the method in order to get true in both cases?

like image 511
Sergio Avatar asked Dec 23 '22 10:12

Sergio


1 Answers

Your condition is too simple... High level idea is, that for each row from a and b pick a row and then identify whether it is the same, so you need 3 loops...

code:

public class SameRowFinder {

    public static void main(String[] args){
        int a[][] = {{1,2},{3,4}};
        int b[][] = {{1,2}, {7,8}};
        System.out.println(hasSameRow(a, b));

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

    private static boolean hasSameRow(int[][] a, int[][] b) {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < b.length; j++) {
                if (isSameRow(a[i], b[j])) {
                    System.out.printf("Same rows are %d and %d (0-based).%n", i, j);
                    return true;
                }
            }
        }
        return false;
    }

    private static boolean isSameRow(int[] row1, int[] row2) {
        if (row1.length != row2.length) {
            throw new IllegalArgumentException("rows with different length");
        }
        for (int i = 0; i < row2.length; i++) {
            if (row1[i] != row2[i]) {
                return false;
            }
        }
        return true;
    }
}

Also you do not need to write your own function for array compare, but use Arrays.equal(int[], int[]), but it will just hide 3rd loop. Method above throws runtime exception in case of different length of arrays. It's definitelly worth look at Arrays.equal(int[], int[]) implementation for some tips (check for equality + null checks).

like image 52
Betlista Avatar answered Jan 11 '23 23:01

Betlista