Instantly share code, notes, and snippets.

# RLGGHC/tony_chen.rbSecret forked from anonymous/tony_chen.rb Created Dec 3, 2009

What would you like to do?
 # Loops through coefficient array in order # => If the coefficent is 0, skip to next term # => Get operator value and absoluete coefficent value # => Appends the term x^ to pretty print string # => Return pretty print string or 0 if pretty print string is empty class Polynomial def initialize(coefficient_array) raise ArgumentError, 'Need at least 2 coefficients' if coefficient_array.size < 2 @coefficient_array = coefficient_array end def pretty_print print_string = "" coefficient_array = @coefficient_array current_coefficient = @coefficient_array.size coefficient_array.each_with_index do |coefficient, term| current_coefficient -= 1 next if coefficient == 0 operator = get_operator_by_coefficient_and_term(coefficient, term) coefficient = coefficient.abs coefficient = "" if coefficient.abs == 1 case current_coefficient when 0 print_string << "#{operator}#{coefficient}" when 1 print_string << "#{operator}#{coefficient}x" else print_string << "#{operator}#{coefficient}x^#{current_coefficient}" end end # empty string if the array only passes in 0's print_string == "" ? "0" : print_string end def get_operator_by_coefficient_and_term(coefficient, term) if coefficient > 0 if first_term?(term) "" else "+" end elsif coefficient < 0 "-" else "" end end def first_term?(term) term == 0 end def to_s pretty_print 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([-5]).to_s