Skip to content

Instantly share code, notes, and snippets.

@LizardLeliel
Last active August 29, 2015 14:12
Show Gist options
  • Save LizardLeliel/bb5ac6dace69c4ce7ba6 to your computer and use it in GitHub Desktop.
Save LizardLeliel/bb5ac6dace69c4ce7ba6 to your computer and use it in GitHub Desktop.
Amazing. Happy new year!
class Vec < Array
def initialize(ary)
super(@vec = ary)
end
def *(scalar)
Vec.new (
@vec.map { |element|
element * scalar
}
)
end
def +(otherVec)
Vec.new(@vec.length).fill { |n|
@vec[n] + otherVec[n]
}
end
def dotProduct(otherVec)
m = 0
@vec.each_index do |n|
m += (@vec[n] * otherVec[n])
end
return m
end
def self.dotProduct(vec1, vec2)
m = 0
vec1.each_index do |n|
m += (vec1[n] * vec2[n])
end
return m
end
end
class Matrix2byN
def initialize(row1, row2)
throw :inequalColumsn if row1.length != row2.length
@row1 = Vec.new(row1)
@row2 = Vec.new(row2)
end
def [](n)
return @row1 if n == 0
return @row2 if n == 1
throw(:OutOfBounds!)
end
def +(otherMatrix)
return Matrix2byN.new(
row1 + otherMatrix[0],
row2 + otherMatrix[1]
)
end
def *(otherMatrix)
z = Matrix.new(Vec.new(Array.new(2)), Vec.new(
Array.new(otherMatrix[0].length)))
return Matrix2by2.new(z[0], z[1])
end
def printMatrix()
print ('| ')
@row1.each do |n|
print n.to_s + ' '
end
puts("|")
print ('| ')
@row2.each do |n|
print n.to_s + ' '
end
puts("|")
end
end
m = Vec.new([1,4,6])
puts m.to_s
puts (m*2).to_s
puts m.to_s
m *= 3
puts m.to_s
puts (m+[10,10,10]).to_s
puts (Vec.new([1,2,3]).dotProduct([1,2,3])).to_s
puts (Vec.dotProduct([1,2,3],[1,2,3])).to_s
abc = Matrix2byN.new([1,2,3,4], [9,0,1,1])
abc.printMatrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment