Skip to content

Instantly share code, notes, and snippets.

@jsborjesson
Created July 12, 2017 20:16
Show Gist options
  • Save jsborjesson/e1bd00347ccaa9f9a4bc5367f880cf39 to your computer and use it in GitHub Desktop.
Save jsborjesson/e1bd00347ccaa9f9a4bc5367f880cf39 to your computer and use it in GitHub Desktop.
class Matrix
def initialize(rows = [])
@rows = rows
end
def [](x, y)
@rows.fetch(y, [])[x]
end
def []=(x, y, value)
(@rows[y] ||= [])[x] = value
align
end
def rotate
self.class.new(@rows.transpose.map(&:reverse))
end
def find(value)
@rows.each_with_index do |row, y|
row.each_with_index do |val, x|
return [x, y] if val == value
end
end
nil
end
private
def align
@rows.map! { |row| Array(row) }
@rows.map! { |row| row.concat([nil] * (width - row.length)) }
end
def width
@rows.map(&:length).max
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment