Skip to content

Instantly share code, notes, and snippets.

@wikjez
Created May 13, 2019 00:08
Show Gist options
  • Save wikjez/c508edb65083fd4b4f4f0ff67357b1f7 to your computer and use it in GitHub Desktop.
Save wikjez/c508edb65083fd4b4f4f0ff67357b1f7 to your computer and use it in GitHub Desktop.
Polynomial Manipulation in Ruby
class Polynomial
# maps e.g. {x: 1, y: 2} => 3 which corresponds to term 3 * x ** 1 * y ** 2
attr_reader :coefficients
def initialize(coefficients = {})
puts @coefficients.inspect
@coefficients = coefficients.reject do |_index, coefficient|
coefficient == 0
end
end
def +(summand)
Polynomial.new(hash_sum(coefficients, summand.coefficients))
end
def -(subtrahend)
self + (-subtrahend)
end
def -@
Polynomial.new(Hash[@coefficients.map { |key, value| [key, -value] }])
end
def *(factor)
case factor.coefficients.size
when 0
0
when 1
factor_multi_index = factor.coefficients.keys.first
factor_coefficient = factor.coefficients.values.first
Polynomial.new(
Hash[
@coefficients.map do |multi_index, coefficient|
[hash_sum(multi_index, factor_multi_index),
coefficient * factor_coefficient]
end
]
)
else
product = self
factor.coefficients.each do |multi_index, coefficient|
product *= Polynomial.new(multi_index => coefficient)
end
product
end
end
private
def hash_sum(*hashes)
sum = {}
hashes.each do |hash|
hash.each do |key, value|
sum[key] ||= 0
sum[key] += value
sum.delete(key) if sum[key] == 0
end
end
sum
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment