Skip to content

Instantly share code, notes, and snippets.

@workmad3
Created October 20, 2015 23:20
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 workmad3/c7cbf486a96a6fecb5ac to your computer and use it in GitHub Desktop.
Save workmad3/c7cbf486a96a6fecb5ac to your computer and use it in GitHub Desktop.
class Coefficient
def initialize(coefficient, power)
@coefficient = coefficient
@power = power
end
def format_coefficient
case @coefficient.abs
when 1
""
else
"#{@coefficient.abs}"
end
end
def format_power
case @power
when 0
""
when 1
"x"
else
"x^#{@power}"
end
end
def sign
if @coefficient < 0
"-"
elsif @coefficient > 0
"+"
end
end
def to_s
if @coefficient == 0
""
else
"#{sign}#{format_coefficient}#{format_power}"
end
end
end
class Polynomial
def initialize(coefficients)
@coefficients = coefficients.map.with_index {|coefficient, idx| Coefficient.new(coefficient, idx)}
end
def to_s
@coefficients.join("").gsub(/^\+/, '')
end
end
puts Polynomial.new([3, 4, -2, 1, 0, 1, 2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment