How to sum the corners of a matrix in Ruby

2 Answers

0 votes
# Returns the sum of the four corner elements of a matrix.
#
# Example matrix:
# 1  2  3  4
# 5  6  7  8
# 9 10 11 12
#
# Corners:
# 1 (top-left)
# 4 (top-right)
# 9 (bottom-left)
# 12 (bottom-right)
#
# Sum = 1 + 4 + 9 + 12 = 26
def sum_corners(matrix)
  # Return 0 if the matrix is empty.
  return 0 if matrix.empty? || matrix[0].empty?

  rows = matrix.length
  cols = matrix[0].length

  # Add the four corner elements.
  matrix[0][0] +
    matrix[0][cols - 1] +
    matrix[rows - 1][0] +
    matrix[rows - 1][cols - 1]
end

# Example usage
matrix = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12]
]

puts "Sum of corners: #{sum_corners(matrix)}"


# run:
# 
# Sum of corners: 26
#

 



answered Oct 11 by avibootz
0 votes
# Returns the sum of the four corner elements of a matrix.
#
# Example matrix:
# 1  2  3  4
# 5  6  7  8
# 9 10 11 12
#
# Corners:
# 1 (top-left)
# 4 (top-right)
# 9 (bottom-left)
# 12 (bottom-right)
#
# Sum = 1 + 4 + 9 + 12 = 26
# Returns the sum of unique corner elements.
def sum_corners(matrix)
  return 0 if matrix.empty? || matrix[0].empty?

  rows = matrix.length
  cols = matrix[0].length

  corners = [
    [0, 0],
    [0, cols - 1],
    [rows - 1, 0],
    [rows - 1, cols - 1]
  ]

  corners.uniq.sum { |r, c| matrix[r][c] }
end

# Example usage
matrix = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12]
]

puts "Sum of corners: #{sum_corners(matrix)}"


# run:
# 
# Sum of corners: 26
#

 



answered Oct 11 by avibootz
...