简体   繁体   中英

How can I check if two 2D Arrays are equal using recursion? Java

So I tried this solution but I dont get why it isnt working. It has something to do with the second method I believe. Does anyone know?



public static boolean sonIguales(int arre1[][],int ren1,int col1,int arre2[][],int col2, int ren2){
        boolean bandera = false;
        if(ren1!=ren2 || col1 != col2 || col1==0 || ren1==0){
            return bandera;
        }
        else{
            bandera = sonIgual(0,0,col1,ren1,arre1,arre2);
        }
        return bandera;
    }
    
    private static boolean sonIgual(int c, int r, int col, int ren, int arre1[][],int arre2[][]){
        if(r < ren){
            if(c < col){
                if(arre1[r][c]-arre2[r][c]==0){
                    
                    sonIgual(c+1,r,col,ren,arre1,arre2);
                }else{
                    return false;
                }
            }else{
            
            sonIgual(0,r+1,col,ren,arre1,arre2);
            }
        
        }
            return true;
    }

you're not returning result of comparison properly, you can modify it like this:

private static boolean sonIgual(int c, int r, int col, int ren, int arre1[][], int arre2[][]) {
    if (r < ren) {
        if (c < col) {
            if (arre1[r][c] != arre2[r][c]) { // don't use - for comparison, you can hit underflow
                return false;
            }
            return sonIgual(c + 1, r, col, ren, arre1, arre2); // return result of recursive call
        }
        return sonIgual(0, r + 1, col, ren, arre1, arre2); // return result of recursive call
    }
    return true; // this is returned when we reached the end of 2d array and non of the checks before failed, so arrays actually the same
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM