Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Created November 28, 2009 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RLGGHC/244320 to your computer and use it in GitHub Desktop.
Save RLGGHC/244320 to your computer and use it in GitHub Desktop.
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