Skip to content

Instantly share code, notes, and snippets.

Created December 17, 2009 06:49
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save anonymous/258571 to your computer and use it in GitHub Desktop.
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment