Created
December 4, 2009 09:08
-
-
Save branch14/248921 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 Polynomial | |
def initialize(coeffs) | |
raise ArgumentError.new("Need at least 2 coefficients.") if coeffs.size < 2 | |
@coeffs = coeffs | |
end | |
def to_s | |
output = [] | |
coeffs = @coeffs.dup | |
coeffs.size.times do |index| | |
coeff = coeffs.pop | |
if coeff != 0 | |
output << "^#{index}" if index > 1 | |
output << 'x' if index > 0 | |
output << coeff | |
output << '+' if coeff > 0 and | |
coeffs.select { |c| c != 0 }.size > 0 | |
end | |
end | |
output.reverse.join | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment