-
-
Save anonymous/7a6ea014f0dc5758068a to your computer and use it in GitHub Desktop.
class that pretty-prints polynomials
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 | |
attr_accessor :expression | |
def initialize(coeffs) | |
bConstant = true #Print constant value of the polynomial | |
bPower = false #Print variable x with its power > 1 | |
bSign = false #Print + as it does not get printed while printing positive integer | |
index = 0 #Contains power of the variable x in polynomial | |
expression = "" #Polynomial expression to be created in reverse order | |
#Start creating polynomial from least power of x to | |
#highest power of x in reverse order | |
coeffs.reverse_each do |coeff| | |
#Print + sign if required for the previous coefficient | |
expression += (bSign && coeff!=0) ? "+" : "" | |
#For an element of polynomial Ax^N print "^N" in reverse | |
#order where N>1 and A!=0 | |
expression += (bPower && coeff!=0) ? "#{index}^" : "" | |
if bConstant | |
#Print constant term of polynomial if non-zero | |
expression += (coeff != 0) ? "#{coeff}".reverse : "" | |
bConstant = false | |
else | |
#For an element of polynomial Ax^N print "Ax" in reverse order where A!=0 | |
#Handle special cases of A==-1 and A==1 | |
expression += (coeff != 0) ? ( coeff ==1?"x":(coeff ==-1?"x-":"#{coeff}x".reverse)): "" | |
bPower = true | |
end | |
#If current coefficient is positive we need to print the '+' sign | |
#while printing next higher term of polynomial | |
#'-' sign for current coefficient gets printed while printing the number | |
if coeff != 0 | |
bSign= (coeff>0) ? true : false | |
end | |
#increment power of variable x to next level | |
index += 1 | |
end | |
if bPower | |
#Handle the case when all the coefficients are zero | |
@expression = (expression!="") ? expression.reverse : "0" | |
elsif | |
#raise exception if there are less than 2 coefficients | |
raise ArgumentError, "Need at least 2 coefficients" | |
end | |
end | |
def to_s | |
return @expression | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment