Skip to content

Instantly share code, notes, and snippets.

Created December 21, 2009 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/260985 to your computer and use it in GitHub Desktop.
Save anonymous/260985 to your computer and use it in GitHub Desktop.
#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