Created
December 21, 2009 15:13
-
-
Save anonymous/260985 to your computer and use it in GitHub Desktop.
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 is compact version of my previous solution <http://gist.github.com/258571> | |
# If compactness is what this challange looking for then this would be suffice | |
# However I would not recommend as it is not readable though it passes all the tests | |
# Same logic as in <http://gist.github.com/258571> but written to be compact | |
class Polynomial | |
def initialize(coefficients) | |
s = false; p = 0; @expression = ""; | |
coefficients.reverse_each do |c| | |
if c!=0 | |
@expression += (s ? "+" : "") + (p>1 ? "#{p}^" : "") + (p>0 ? "x" : "") + ((p >0 && c.abs==1) ? "" : ("#{c}".reverse)) + ((c==-1) ? "-" : "") | |
s = (c>0) ? true : false | |
end | |
p = p + 1 | |
end | |
raise ArgumentError, "Need at least 2 coefficients" unless p > 1 | |
end | |
def to_s | |
return @expression=="" ? "0" : @expression.reverse # Return 0 as required | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment