Skip to content

Instantly share code, notes, and snippets.

@taylorlapeyre
Last active August 29, 2015 14:15
Show Gist options
  • Save taylorlapeyre/04d2df7290bd80a70dcd to your computer and use it in GitHub Desktop.
Save taylorlapeyre/04d2df7290bd80a70dcd to your computer and use it in GitHub Desktop.
class Matrix
attr_reader :elements
def initialize(elements)
@elements = elements
end
def dimensions
{ rows: @elements.first.count, cols: @elements.count }
end
def can_be_multiplied_with(other_matrix)
dimensions[:rows] == other_matrix.dimensions[:cols]
end
def *(other_matrix)
if can_be_multiplied_with other_matrix
new_elements = (0...dimensions[:cols]).map do |k|
(0...dimensions[:rows]).map do |i|
(0...dimensions[:rows]).map do |j|
@elements[k][j] * other_matrix.elements[j][i]
end.reduce(:+)
end
end
Matrix.new(new_elements)
else
throw "Matrix dimensions do not match up; Cannot multiply."
end
end
# Ignore, just necessary to do `m1 * m2`
def coerce(other)
return self, other
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment