secret
Last active — forked from pantras/Philippe.Antras.rb

  • Download Gist
Philippe.Antras.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 57 58
class Polynomial
def initialize(coefficients)
if (coefficients.size < 2)
raise ArgumentError, "Need at least 2 coefficients."
end
@poly_str = convert(coefficients)
end
 
# convert the array of coefficient into a string containing the polynomial it represents
def convert(coefficients)
result = nil
power = coefficients.size - 1
coefficients.each { |coeff|
if (coeff != 0)
factor = build_factor(coeff, power)
 
if (nil == result)
result = factor
else
result += "+" + factor
end
end
power -= 1
}
 
if (nil == result)
result = "0"
else
# remove pointless + (in front of negative values)
result.gsub!(/\+\-/, "-")
end
return result
end
 
# build factor from coefficient and power using mathematical rules
def build_factor(coeff, power)
if (0 == power)
factor = coeff.to_s
else
if (1 == coeff)
factor = "x"
elsif (-1 == coeff)
factor = "-x"
else
factor = coeff.to_s + "x"
end
if (power > 1)
factor += "^"
factor += power.to_s
end
end
return factor
end
 
def to_s
return @poly_str
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.