Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Forked from pharrington/paulharrington.rb
Created December 4, 2009 06:52
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/b80176579fb53fbce4a5 to your computer and use it in GitHub Desktop.
Save RLGGHC/b80176579fb53fbce4a5 to your computer and use it in GitHub Desktop.
class Polynomial
def initialize ary
raise ArgumentError, "Need at least 2 coefficients" unless ary.size > 1
@coeffs = ary.reverse # low order terms first
@coeffs.pop while @coeffs.last == 0
end
def to_s
return "0" if @coeffs.all? {|c| c == 0} # short circuit if all terms are 0
str = ""
@coeffs.each_with_index do |coeff, exp|
unless coeff == 0 # skip terms that are 0
op = if coeff == @coeffs.last && coeff > 0 # don't display the sign of the last term if positive
:""
else
coeff > 0 ? :+ : :-
end
coeff_str = coeff.abs == 1 ? :"" : coeff.abs.to_s # don't display the coefficient if it's 1
exp_str = exp > 1 ? "^#{exp}" : :"" # don't display the exponent if it's 1
var = exp > 0 ? :x : :"" # the first term is a constant; do not display a variable
str.insert 0, "" << op << coeff_str << var << exp_str
end
end
str
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment