Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,683 questions

55,435 answers

573 users

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

1 Answer

0 votes
# 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

 



answered Aug 5 by avibootz
...