Created
November 28, 2009 01:12
-
-
Save RLGGHC/244320 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 args=[] | |
raise ArgumentError, "Need at least 2 coefficients." if args.size < 2 | |
@max_exp = args.size - 1 | |
@poly = "" | |
args.each_with_index do |coef, index| | |
# Code reading 101 : 'coef' stands for 'coefficient'. | |
next if coef.zero? | |
@coef = coef | |
@index = index | |
add_sign | |
add_coef | |
add_exp | |
end | |
@poly = "0" if @poly.empty? | |
end | |
def to_s | |
@poly | |
end | |
private | |
def add_sign | |
if @index > 0 # If this isn't the first argument | |
if @coef > 0 | |
@poly += "+" | |
else | |
@poly += "-" | |
end | |
else # If it's the first argument, we don't care about '+' | |
if @coef < 0 | |
@poly += "-" | |
end | |
end | |
end | |
def add_coef | |
coef = @coef.abs # We only care about the absolute value, here. | |
return if coef == 1 | |
@poly += coef.to_s | |
end | |
def add_exp | |
exponent = @max_exp - @index # Size of the array minus where we are in the array | |
return if exponent.zero? | |
if exponent > 1 | |
@poly += "x^#{exponent}" | |
else | |
@poly += "x" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment