-
-
Save RLGGHC/f1686697de251e25a9b8 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
require 'enumerator' | |
class Coefficient | |
def initialize(term, index, highest_power) | |
@term = term | |
@index = index | |
@highest_power = highest_power | |
end | |
def to_s | |
multiplier.to_s + exponent.to_s unless @term == 0 # if the term is 0 then there should be no coefficient | |
end | |
private | |
def multiplier | |
if @term == -1 | |
"-" # the coefficient should be -x^a rather than -1x^a | |
elsif @term == 1 | |
"+" unless first_term? # because we don't need a leading + | |
elsif @term < -1 | |
@term.to_s # the negative sign will aready be there for us | |
elsif @term > 1 | |
"+" + @term.to_s | |
end | |
end | |
def exponent | |
if power == 1 | |
"x" # because x^1 is just x | |
elsif power != 0 | |
"x^" + power.to_s | |
end | |
end | |
def first_term? | |
@index == 0 | |
end | |
def power | |
@highest_power - @index | |
end | |
end | |
class Polynomial | |
def initialize(terms) | |
@terms = terms | |
enough_terms? | |
@highest_power = (terms.size - 1) | |
@coefficients = coefficients.delete_if {|x| x.nil?} | |
end | |
def to_s | |
if @coefficients.size == 0 | |
"0" | |
else | |
@coefficients.join | |
end | |
end | |
private | |
def coefficients | |
@terms.enum_with_index.map do |term, index| | |
Coefficient.new(term, index, @highest_power).to_s | |
end | |
end | |
def enough_terms? | |
raise ArgumentError, "Need at least 2 coefficients" if @terms.size < 2 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment