Skip to content

Instantly share code, notes, and snippets.

@vaskoz
Created November 26, 2009 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaskoz/243267 to your computer and use it in GitHub Desktop.
Save vaskoz/243267 to your computer and use it in GitHub Desktop.
# My solution to: https://gist.github.com/280aa4797a580fb8ae75
class Polynomial
class Term
attr_reader :power, :coefficient
def initialize(power, coefficient)
@power = power
@coefficient = coefficient
end
def to_s
return "" if coefficient.zero?
sign = (coefficient > 0) ? "+" : "-"
return "#{sign}#{coefficient.abs}x^#{power}"
end
end
def initialize(coefficients)
raise ArgumentError, "Need at least 2 coefficients." if coefficients.size < 2
@terms = []
coefficients.each_with_index { |coef, index| @terms << Term.new(coefficients.size - index - 1, coef) }
end
def to_s
s = String.new
@terms.each { |t| s << t.to_s }
s = s.gsub(/\+1/, '+').gsub(/\-1/, '-').gsub(/\^1/, '').gsub(/x\^0/, '')
s = s[1..-1] if s.start_with? "+"
return s.size == 0 ? "0" : s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment