Skip to content

Instantly share code, notes, and snippets.

@ravikumar-n
Forked from citizen428/polynomial.rb
Created June 11, 2010 14:43
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 ravikumar-n/434558 to your computer and use it in GitHub Desktop.
Save ravikumar-n/434558 to your computer and use it in GitHub Desktop.
class Polynomial
def initialize(coefficients)
raise ArgumentError, "Need at least 2 coefficients" if coefficients.size < 2
@co = coefficients
@powers = Array.new(@co.size - 2) { |i| "x^#{i+2}"}.reverse << 'x' << nil
end
def to_s
return "0" if @co.all? { |c| c.zero? } # not much to do in this case
@co.zip(@powers).map do |el|
next if el[0] == 0
# #{sign}#{value or empty string}#{x^y}
"#{(el[0] > 0 ? '+' : '-')}#{(v = el[0].abs) == 1 && el[1] ? '' : v}#{el[1]}"
end.join.gsub(/^\+/,'') # remove eventual leading '+'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment