Last active
August 29, 2015 14:15
-
-
Save taylorlapeyre/04d2df7290bd80a70dcd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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