Skip to content

Instantly share code, notes, and snippets.

@manzyuk
Created December 8, 2009 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save manzyuk/f117a2a9671ba964e664 to your computer and use it in GitHub Desktop.
Save manzyuk/f117a2a9671ba964e664 to your computer and use it in GitHub Desktop.
solution to Ruby quiz
class ArgumentError < StandardError
end
class Polynomial
def initialize(coeffs)
raise ArgumentError, "Need at least 2 coefficients" unless coeffs.length > 1
@coeffs = coeffs
end
def to_s
# `pairs' is an array that encodes non-zero terms occuring in the polynomial.
pairs = @coeffs.reverse.each_with_index.reject { |c, i| c == 0 }.reverse
if pairs.empty?
# If there are no non-zero terms, then we are dealing with the zero polynomial.
"0"
else
# Otherwise format each term, join all the terms interspersing them
# with the "+" sign and replace all occurences of "+-" with "-".
pairs.map { |c, i| term c, i }.join("+").gsub(/\+-/, "-")
end
end
private
# Format the term cx^i approriately for pretty-printing.
# Omit the coeffiecient c if it is -1 or 1, but leave it
# in the constant term.
def term(c, i)
d = case c
when -1 then "-"
when 1 then ""
else "#{c}"
end
case i
when 0 then "#{c}"
when 1 then "#{d}x"
else "#{d}x^#{i}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment