Skip to content

Instantly share code, notes, and snippets.

@chrisjones
Created November 27, 2009 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisjones/243922 to your computer and use it in GitHub Desktop.
Save chrisjones/243922 to your computer and use it in GitHub Desktop.
Solution for RPCFN #4
#!/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