Skip to content

Instantly share code, notes, and snippets.

@pantras
Created December 17, 2009 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pantras/43bdd25b93c2ac7f663b to your computer and use it in GitHub Desktop.
Save pantras/43bdd25b93c2ac7f663b to your computer and use it in GitHub Desktop.
class Polynomial
def initialize(coefficients)
if (coefficients.size < 2)
raise ArgumentError, "Need at least 2 coefficients."
end
@poly_str = convert(coefficients)
end
# convert the array of coefficient into a string containing the polynomial it represents
def convert(coefficients)
result = nil
power = coefficients.size - 1
coefficients.each { |coeff|
if (coeff != 0)
factor = build_factor(coeff, power)
if (nil == result)
result = factor
else
result += "+" + factor
end
end
power -= 1
}
if (nil == result)
result = "0"
else
# remove pointless + (in front of negative values)
result.gsub!(/\+\-/, "-")
end
return result
end
# build factor from coefficient and power using mathematical rules
def build_factor(coeff, power)
if (0 == power)
factor = coeff.to_s
else
if (1 == coeff)
factor = "x"
elsif (-1 == coeff)
factor = "-x"
else
factor = coeff.to_s + "x"
end
if (power > 1)
factor += "^"
factor += power.to_s
end
end
return factor
end
def to_s
return @poly_str
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment