Instantly share code, notes, and snippets.

# pantras/Philippe.Antras.rbSecret Created Dec 17, 2009

 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
to join this conversation on GitHub. Already have an account? Sign in to comment