Instantly share code, notes, and snippets.

# rymai/remycoutable.rbSecret Created Dec 13, 2009

What would you like to do?
 # Ruby Programming Challenge For Newbies # Solution for RPCFN: Ruby**Fun (#4) # # Creator : Rémy COUTABLE 2009 (http://remycoutable.fr) class Polynomial attr_reader :coeffs # coeffs should be an Array of relative integer def initialize(coeffs) raise ArgumentError, "Need at least 2 coefficients." if coeffs.size < 2 @coeffs = coeffs.reverse end def to_s @result = "" (@coeffs.size - 1).downto(0) do |power| @result += print_coeff_and_power(@coeffs[power], power) end @result.empty? ? "0" : @result end private def print_coeff_and_power(coeff, power) "#{print_sign(coeff)}#{print_coeff(coeff, power)}#{print_power(power, coeff)}" end # only display "+" for a positive integer, and not for the first coeff def print_sign(coeff) "+" if coeff > 0 && !@result.empty? end # coeff is a relative integer def print_coeff(coeff, power) (coeff == -1 && power > 0) ? "-" : coeff if display_coeff?(coeff, power) end def display_coeff?(coeff, power) return case coeff when 0 false when 1 power == 0 else true end end # power is an integer def print_power(power, coeff) "x#{"^#{power}" if power > 1}" if power > 0 && coeff != 0 end end puts Polynomial.new([-3,-4,1,0,6]).to_s puts Polynomial.new([1,0,2]).to_s puts Polynomial.new([-1,-2,3,0]).to_s puts Polynomial.new([0,0,0]).to_s puts Polynomial.new([0,1,2,3,4]).to_s puts Polynomial.new([-5,-4,-3,-2,-1]).to_s puts Polynomial.new([3,2,1]).to_s