public
Last active

RPCFN4 - polynomials

  • Download Gist
rpcfn4.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
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
@poly += (@coef > 0 ? "+" : "-")
else # If it's the first argument, we don't care about '+'
@poly += "-" if @coef < 0
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?
@poly += (exponent > 1 ? "x^#{exponent}" : "x")
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.