Tank

mail@pastecode.io avatar
unknown
java
a month ago
1.5 kB
3
Indexable
Never
public class Change {
    public static void main(String[] args) {
        int [] [] mat = {
                {2,7,6},
                {9,5,1},
                {4,3,8}
        };
        System.out.println(isMagicSquare(mat));

    }

    public static boolean isMagicSquare(int [][] a) {
//		check matrix baris = kolom
        for (int i = 0 ; i <a.length ; i ++) {
            if (a[i].length != a.length) {
                return false;
            }
        };
//jumlah tiap baris sama
//referensi jumlah nya
        int sumRef = 0;
        for (int i = 0 ; i<a[0].length ; i++) {
            sumRef += a[0][i];
        }

//cek jumlah tiap baris apakah sama
        int sumBaris = 0 ;
        for (int i = 0 ; i<a.length; i++) {
            for (int j = 0 ; j <a.length ; j++) {
                sumBaris += a[i][j];

            }if(sumRef!=sumBaris)return false;
            sumBaris=0;
        }

//cek jumlah tiap kolom apakah sama
        int sumKolom =0;
        for (int i = 0 ; i<a.length; i++) {
            for (int j = 0 ; j <a.length ; j++) {
                sumKolom += a[j][i];
            }if(sumRef!=sumKolom) return false;
            sumKolom=0;
        }
//cek jumlah diagonal kiri ke kanan
        int sum3=0;
        for (int i = 0 ; i<a.length; i++) {
            sum3 += a[i][i];
        }if (sum3!= sumRef)return false;

        int sum4 = 0;
        for (int i = 0 ; i<a.length ; i++) {
            sum4 += a[i][a.length-1-i];
        }if (sum4!= sumRef)return false;
        return true;
    }
}
Leave a Comment