/gist:7877d8c0e89049eae3ab Secret
Created
December 9, 2009 00:08
-
-
Save RLGGHC/7877d8c0e89049eae3ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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