-
-
Save RLGGHC/b80176579fb53fbce4a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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