Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Forked from anonymous/polynomial.rb
Created December 15, 2009 01:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save RLGGHC/256620 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment