-
-
Save anonymous/5902f4034b47a012665c 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
# This class prepares a pretty-print version of a polynomial with a minimum of 2 coefficients | |
# | |
class Polynomial | |
# Create the polynomial object and store the coefficients | |
# | |
def initialize(args) | |
raise ArgumentError, "Need at least 2 coefficients" if args.length < 2 | |
@args = args | |
end | |
# Returns a string version of the polynomial, simplifies coefficients of 1x^n to x^n, | |
# simplifies x^1 to x and ax^0 to a. Doesn't include elements with a coefficient of 0. | |
# If all coefficients = 0, returns "0". | |
# | |
def to_s | |
polynomial = [] | |
@args.each_with_index do |coefficient, index| | |
unless coefficient.zero? | |
polynomial << coefficient.to_s + "x^" + (@args.length - 1 - index).to_s | |
end | |
end | |
unless polynomial.empty? | |
return polynomial.join("+").gsub(/\+\-/, '-').gsub(/(^|[\+\-])[1]x/, '\1x').gsub("x^1", 'x').gsub("x^0", '') | |
# ^| in regex handles case where 1x is at beginning of line, otherwise it's -1x and is covered by rest of regex | |
else | |
return "0" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment