secret
Last active

solution to Ruby quiz

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.