# This program checks whether a square matrix is a magic square.
# A magic square has:
# 1. All rows summing to the same value
# 2. All columns summing to the same value
# 3. Both main diagonals summing to that same value
# 4. The matrix must be square
# Compute the sum of each row
def row_sums(matrix)
matrix.map { |row| row.sum }
end
# Compute the sum of each column
def column_sums(matrix)
size = matrix.size
(0...size).map { |col| matrix.map { |row| row[col] }.sum }
end
# Compute the two diagonal sums
def diagonal_sums(matrix)
size = matrix.size
main_diag = (0...size).map { |i| matrix[i][i] }.sum
secondary_diag = (0...size).map { |i| matrix[i][size - 1 - i] }.sum
[main_diag, secondary_diag]
end
# Check whether the matrix is a magic square
def magic_square?(matrix)
return false if matrix.empty?
return false unless matrix.all? { |row| row.size == matrix.size }
target = matrix[0].sum
return false unless row_sums(matrix).all? { |s| s == target }
return false unless column_sums(matrix).all? { |s| s == target }
diag1, diag2 = diagonal_sums(matrix)
return false unless diag1 == target && diag2 == target
true
end
# Matrix
matrix = [
[8, 1, 6],
[3, 5, 7],
[4, 9, 2]
]
puts "Matrix:"
matrix.each { |row| p row }
puts "\nIs magic square? #{magic_square?(matrix)}"
=begin
run:
Matrix:
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]
Is magic square? true
=end