Instantly share code, notes, and snippets.

# allegrojm/johnmcdonald.rbSecret Created Dec 1, 2009

What would you like to do?
 # # pretty polynomial print # # - passed all unit tests # class Polynomial attr_reader :coefficients def initialize(coefficients) raise ArgumentError, 'Need at least 2 coefficients' if coefficients.size < 2 coefficients.each do |c| raise ArgumentError, 'Invalid coefficient ' + c.to_s if c.class != Fixnum end @coefficients = coefficients end def to_s str ||= String.new @coefficients.each_index do |i| # # Checking the conditions: # - if 1st coefficient pos or neg # - if subsequent coefficients pos or neg # - if a coefficient is zero # - if a coefficient is a '1' (pos or neg) # - if coefficient of zero term (x^0) is '1' # - check the degree of the term (add '^') case when @coefficients[i] == 0 # if all zeroes str << '0' if str == '' when i == @coefficients.size-1 # if the last cofficient str << '+' unless @coefficients[i] < 0 # is positive and is the last coefficient (constant), add '+' str << @coefficients[i].to_s # add the last coefficient else str << '+' unless i == 0 or @coefficients[i] < 0 # is positive and not first coefficient, add '+ str << '-' if @coefficients[i] < 0 and @coefficients[i].abs == 1 # is negative, is '1' coefficient, add '-' str << @coefficients[i].to_s unless @coefficients[i].abs == 1 # don't add a '1' coefficient str << 'x' str << '^' + (@coefficients.size-(i+1)).to_s if i < @coefficients.size-2 # check the degree end # end case end # end do str # return the string end end p = Polynomial.new([-3,-4,1,0,6]) puts p.to_s p = Polynomial.new([0,0,-0]) puts p.to_s p = Polynomial.new([-20,0,18,-12,7,-4,0,-3,-4,1,-1,-6]) puts p.to_s p = Polynomial.new([-20,0]) puts p.to_s
to join this conversation on GitHub. Already have an account? Sign in to comment