Skip to content

@RLGGHC /olivernn secret forked from olivernn/olivernn
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.