How to check whether a matrix is a magic square or not in Swift

1 Answer

0 votes
import Foundation

// Function to check if the matrix is a magic square
func isMagicSquare(_ matrix: [[Int]]) -> Bool {
    let size = matrix.count
    var sumDiagonal1 = 0
    var sumDiagonal2 = 0

    // Calculate the sum of the primary diagonal
    for i in 0..<size {
        sumDiagonal1 += matrix[i][i]
    }

    // Calculate the sum of the secondary diagonal
    for i in 0..<size {
        sumDiagonal2 += matrix[i][size - i - 1]
    }

    // If the two diagonals don't have the same sum, it's not a magic square
    if sumDiagonal1 != sumDiagonal2 {
        return false
    }

    // Check sums of each row and column
    for i in 0..<size {
        var sumRow = 0
        var sumCol = 0

        for j in 0..<size {
            sumRow += matrix[i][j]  // Sum of the current row
            sumCol += matrix[j][i]  // Sum of the current column
        }

        // If any row or column sum is not equal to the diagonal sum, it's not a magic square
        if sumRow != sumDiagonal1 || sumCol != sumDiagonal1 {
            return false
        }
    }

    // If all checks pass, it's a magic square
    return true
}

let matrix = [
    [8, 3, 4],
    [1, 5, 9],
    [6, 7, 2]
]

if isMagicSquare(matrix) {
    print("The given matrix is a magic square.")
} else {
    print("The given matrix is NOT a magic square.")
}


/*
run:

The given matrix is a magic square.

*/

 



answered Sep 30 by avibootz
...