Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Forked from allegrojm/johnmcdonald.rb
Created December 2, 2009 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RLGGHC/41a140d8e04206ba5221 to your computer and use it in GitHub Desktop.
Save RLGGHC/41a140d8e04206ba5221 to your computer and use it in GitHub Desktop.
#
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment