public
Last active — forked from Trevoke/rpcfn4.rb

  • 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 47 48 49 50 51 52 53 54 55 56
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.