secret
Last active — forked from /SurajDhakankar.rb

  • Download Gist
SurajDhakankar.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.