public
Last active — forked from /Sunny.Dackie.rb

  • Download Gist
Sunny.Dackie.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
#This class can generate Polynomial for any number of arguments passed
#Comments are welcome
 
class Polynomial
attr_accessor :expression
 
def initialize(coefficients)
s = false; p = 0; e = "";
#Generate Expression in reverse direction
coefficients.reverse_each do |c|
if c!=0
e += s ? "+" : "" #Print + for previous coefficient if required
e += p>1 ? "#{p}^" : "" #Print power term for all x when N>1
e += p>0 ? "x" : "" #Print x term when N>0
e += (p >0 && c.abs==1) ? "" : ("#{c}".reverse) #Print coefficient term for all except when it is +/- 1
e += (c==-1) ? "-" : "" #Print - when coefficient is -1
s = (c>0) ? true : false # ? Required to print + next if there are more higher coefficient
end
p += 1
end
raise ArgumentError, "Need at least 2 coefficients" unless p > 1
@expression=e.reverse #Save Expression in proper order
end
def to_s
return @expression=="" ? "0" : @expression # Return 0 as required
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.