Created
December 20, 2009 10:21
-
-
Save citizen428/260434 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(coefficients) | |
raise ArgumentError, "Need at least 2 coefficients" if coefficients.size < 2 | |
@co = coefficients | |
@powers = Array.new(@co.size - 2) { |i| "x^#{i+2}"}.reverse << 'x' << nil | |
end | |
def to_s | |
return "0" if @co.all? { |c| c.zero? } # not much to do in this case | |
@co.zip(@powers).map do |el| | |
next if el[0] == 0 | |
# #{sign}#{value or empty string}#{x^y} | |
"#{(el[0] > 0 ? '+' : '-')}#{(v = el[0].abs) == 1 && el[1] ? '' : v}#{el[1]}" | |
end.join.gsub(/^\+/,'') # remove eventual leading '+' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment