Instantly share code, notes, and snippets.

# manzyuk/gist:f117a2a9671ba964e664Secret Created Dec 8, 2009

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