In Java, Check For Identical Arrays

import java.util.Scanner;
public class IdenticalArrays{

    public static boolean equals(int[][] m1, int[][] m2){
        if(m1 == m2)
            return true;
        boolean same = false;
        if(m1.length == m2.length){
            same = true;
            for(int i = 0,j; same && m1.length > i; i ++){
                if(m1[i].length == m2[i].length){
                    for(j = 0; same && m1[i].length > j; j ++){
                        if(m1[i][j] != m2[i][j]){
                            same = false;
                            break;
                        }
                    }
                } else {
                    same = false;
                    break;
                }
            }
        }
        return same;
    }

    private static int[][] read(String prompt, Scanner in, final int r, final int c){
        int[][]arr = new int[r][c];
        System.out.print(prompt);
        for(int i = 0,j; r > i; i ++)
            for(j = 0; c > j; j ++)
                arr[i][j] = in.nextInt();
        return arr;
    }

    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        final int r = 3, c = 3;
        int[][]m1 = read("Enter list1:", in, r, c);
        int[][]m2 = read("Enter list2:", in, r, c);
        System.out.printf("The two arrays are %sstrictly identical\n", equals(m1, m2)?"":"not ");
    }
}
Download

Comments

Popular posts from this blog