Created
November 27, 2009 09:23
-
-
Save chrisjones/243922 to your computer and use it in GitHub Desktop.
Solution for RPCFN #4
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
#!/usr/bin/ruby | |
class Polynomial | |
def initialize(coefficients) | |
if coefficients.length < 2 | |
raise ArgumentError, 'Need at least 2 coefficients.' | |
end | |
order = coefficients.length - 1 | |
@poly = "" | |
coefficients.each do |c| | |
unless c == 0 | |
if order != coefficients.length - 1 and c > 0 | |
@poly << "+" | |
end | |
@poly << c.to_s unless c.abs == 1 | |
@poly << "-" if c == -1 | |
@poly << "x" unless order < 1 | |
@poly << "^" + order.to_s unless order < 2 | |
end | |
order -= 1 | |
end | |
end | |
def to_s | |
@poly.empty? ? "0" : @poly | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment