Created
October 20, 2015 23:20
-
-
Save workmad3/c7cbf486a96a6fecb5ac 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
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