Skip to content

Instantly share code, notes, and snippets.

@travisofthenorth
Last active November 17, 2016 17:15
Show Gist options
  • Save travisofthenorth/bf2e4ae75729c49ec4f8a51f15acf619 to your computer and use it in GitHub Desktop.
Save travisofthenorth/bf2e4ae75729c49ec4f8a51f15acf619 to your computer and use it in GitHub Desktop.
Matrix binary search
class Matrix
Coordinate = Struct.new(:x, :y)
def initialize(grid)
@grid = grid
end
def binary_search(n)
row = find_row(n, 0, grid.count - 1)
return nil unless row
col = grid[row].index(n)
return nil unless col
Coordinate.new(row, col)
end
private
attr_reader :grid
def find_row(n, low, high)
return nil if low > high
r = (high + low) / 2
if grid[r][0] <= n
if r == grid.count - 1 || grid[r + 1][0] > n
r
else
find_row(n, r + 1, high)
end
else
find_row(n, low, r - 1)
end
end
end
matrix = Matrix.new([
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50],
[51, 60, 64, 65],
[70, 71, 72, 100]
])
puts matrix.binary_search(16) || 'Not found!'
puts matrix.binary_search(50) || 'Not found!'
puts matrix.binary_search(-1) || 'Not found!'
puts matrix.binary_search(100) || 'Not found!'
puts matrix.binary_search(63) || 'Not found!'
puts matrix.binary_search(64) || 'Not found!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment