secret
Last active — forked from olivernn/olivernn

  • Download Gist
olivernn
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.