Skip to content

Instantly share code, notes, and snippets.

@anolson
Created February 21, 2012 21:52
Show Gist options
  • Save anolson/1879239 to your computer and use it in GitHub Desktop.
Save anolson/1879239 to your computer and use it in GitHub Desktop.
Find saddle points in a matrix
Saddle point found at: [1, 3]
No saddle points found
Saddle point found at: [1, 3]
module SaddlePoint
class Matrix
def initialize(array = [])
@rows = array
end
def saddle_points
saddle_points = []
@rows.each_with_index do |row, column_index|
max_row_value = row.max
indicies(row, max_row_value).each do |row_index|
min_column_value = extract_column(row_index).min
saddle_points << { row: row_index, col: column_index } if max_row_value == min_column_value
end
end
saddle_points
end
def indicies(array, value)
indicies = []
array.each_with_index do |v, i|
indicies << i if v == value
end
indicies
end
def extract_column(index)
@rows.collect do |row|
row[index]
end
end
end
class Printer
def initialize(array = [])
@matrix = Matrix.new(array)
end
def print_saddle_points()
cells = @matrix.saddle_points
puts "No saddle points found" if cells.empty?
cells.each do |cell|
puts "Saddle point found at: [#{cell[:row]}, #{cell[:col]}]"
end
end
end
end
arr1 = [[39, 43, 49, 29, 18],
[30, 47, 24, 29, 15],
[49, 50, 39, 20, 33],
[18, 38, 35, 32, 35],
[29, 44, 18, 34, 44]]
arr2 = [[50, 27, 36, 43, 39],
[36, 14, 35, 40, 19],
[20, 33, 48, 32, 40],
[41, 40, 15, 22, 19],
[21, 24, 24, 31, 18]]
arr3 = [[39, 43, 49, 29, 18],
[30, 47, 24, 29, 15],
[49, 50, 39, 20, 33],
[18, 38, 35, 32, 38],
[29, 44, 18, 34, 44]]
SaddlePoint::Printer.new(arr1).print_saddle_points
SaddlePoint::Printer.new(arr2).print_saddle_points
SaddlePoint::Printer.new(arr3).print_saddle_points
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment