public
Created

  • Download Gist
Sunny.Dackie.Compact.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
 
#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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.