secret
Created — forked from allegrojm/johnmcdonald.rb

  • Download Gist
johnmcdonald.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.