From 857e838ecc6902da8f6ab390bd573b2b8cfe01c6 Mon Sep 17 00:00:00 2001 From: Vytas87 <53813670+Vytas87@users.noreply.github.com> Date: Mon, 16 Sep 2019 14:40:07 +0200 Subject: [PATCH] Update isMagicSquare.java The original code checks only the sums of rows. Therefore, to complete the task, columns and diagonals need to be checked as well. --- chapter-7/isMagicSquare.java | 50 +++++++++++++++++++++++++++++------- 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/chapter-7/isMagicSquare.java b/chapter-7/isMagicSquare.java index 26f6245..59aa104 100644 --- a/chapter-7/isMagicSquare.java +++ b/chapter-7/isMagicSquare.java @@ -7,32 +7,64 @@ public static boolean isMagicSquare(int[][] array) { boolean result = true; - + for (int row = 0; row < array.length; row++) { if (array[row].length != array.length) { result = false; } } - + if (result) { int sum = 0; - + int newSum = 0; + for (int col = 0; col < array.length; col++) { sum += array[0][col]; } - + + // checking rows for (int row = 1; row < array.length; row++) { - int newSum = 0; - - for (int col = 0; col < array[row].length; col++) { + + for (int col = 0; col < array.length; col++) { newSum += array[row][col]; } - + if (sum != newSum) { result = false; } + newSum = 0; + } + + // checking columns + for (int col = 0; col < array.length; col++) { + + for (int row = 0; row < array.length; row++) { + newSum += array[row][col]; + } + + if (sum != newSum) { + result = false; + } + newSum = 0; + } + + // checking diagonal tl - br + for (int row = 0; row < array.length; row++) { + newSum += array[row][row]; + } + if (sum != newSum) { + result = false; + } + newSum = 0; + + // checking diagonal bl - tr + for (int row = 0; row < array.length; row++) { + newSum += array[(array.length - 1) - row][row]; + } + if (sum != newSum) { + result = false; } } - + return result; }