Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Created December 7, 2009 02:26
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/53da49329871173b3405 to your computer and use it in GitHub Desktop.
Save RLGGHC/53da49329871173b3405 to your computer and use it in GitHub Desktop.
class Polynomial < String
def initialize(coefficient_array)
raise ArgumentError, "Need at least 2 coefficients." if coefficient_array.length < 2 #minimum term count
expression = ''; coefficient_array.each_with_index {|c,i| expression += build_term(c,coefficient_array.length-(i+1))} #build expression one term at a time
super(expression.sub(/^\+/,'').sub(/^$/,'0')) # tidy up: (1) remove starting plus sign (2) handle empty expression.
end
private
def build_term(c,e) # c = coefficient : e = current exponent
# build the term only if coefficient is no equal to zero
c != 0 ? "#{build_sign(c)}#{build_coefficient(c)}#{build_variable(e)}#{build_exponent(e)}" : ''
end
def build_sign(c)
c > 0 ? '+' : '-'
end
def build_coefficient(c)
# coefficient is supressed if 1 or -1
c.abs!=1 ? c.abs : ''
end
def build_variable(e)
# variable is supressed if exponent is 0
e>0 ? 'x' : ''
end
def build_exponent(e)
# exponent is supressed if 1 or 0
e>1 ? "^#{e}" : ''
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment