-
-
Save pantras/43bdd25b93c2ac7f663b 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(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