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
#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