Skip to content

@RLGGHC /gist:7877d8c0e89049eae3ab secret forked from manzyuk/gist:f117a2a9671ba964e664
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.