public
Last active — forked from /polynomial.rb

  • Download Gist
polynomial.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
class Polynomial
attr_reader :coeffs
def initialize(coeffs)
raise ArgumentError, "Need at least 2 coefficients", caller if coeffs.length <= 2
@coeffs = coeffs
end
def to_s
polynom = "" #initialize empty string to create polynomial expression
@coeffs.each_with_index do |coeff,index|
exponent = @coeffs.length - index - 1 #countdown exponent value starting from 1 less than number of coefficients passed
if coeff != 0 #Don't do anything if 0 value is passed for current coefficient
polynom += "+" if (coeff >= 0 and polynom != "")
#Add a plus sign if coefficient is positive unless on first item of array or there has been no output so far
polynom += coeff.to_s unless (coeff == 1 and exponent != 0)
#Add the coefficient to polynomial unless is a 1 value or on the final coefficient
polynom.chop! if coeff == -1
#Remove the 1 if the coefficient is -1 (leaving just a minus sign)
polynom += "x" unless exponent == 0
#Add x for all but last coefficient
polynom += "^" + exponent.to_s if exponent > 1
#Add ^exponent for all but last 2 coefficients
end
end
polynom == "" ? "0" : polynom #set polynom to "0" if nothing has been output
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.