Class: Polynomial

Inherits:
Object
  • Object
show all
Defined in:
lib/polynomial_ruby/polynomial.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(coefficients) ⇒ Polynomial

Returns a new instance of Polynomial.



7
8
9
10
11
# File 'lib/polynomial_ruby/polynomial.rb', line 7

def initialize(coefficients)
  raise "At least one coefficient is required" if coefficients.size == 0
  coefficients = coefficients[0...-1] while coefficients[-1] == 0 && coefficients.size > 1
  @coefficients = Array(coefficients)
end

Instance Attribute Details

#coefficientsObject (readonly)

Returns the value of attribute coefficients.



5
6
7
# File 'lib/polynomial_ruby/polynomial.rb', line 5

def coefficients
  @coefficients
end

Instance Method Details

#*(other) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/polynomial_ruby/polynomial.rb', line 30

def *(other)
  if other.kind_of?(Numeric)
    self.class.new(coefficients.map { |c| c * other })
  elsif other.kind_of?(self.class)
    coefficients.map.with_index { |c, idx|
      self.class.new(Array.new(idx, 0) + other.coefficients.map { |o| o * c })
    }.reduce { |sum, p|
      sum + p
    }
  else
    raise "Cannot multiply #{self} by #{other}"
  end
end

#+(other) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/polynomial_ruby/polynomial.rb', line 17

def +(other)
  if other.kind_of?(Numeric)
    self + self.class.new([other])
  elsif other.kind_of?(self.class)
    coef = Array.new([other.degree, degree].max + 1) { |i|
      (other.coefficients[i] || 0) + (coefficients[i] || 0)
    }
    self.class.new(coef)
  else
    raise "Cannot sum #{self} with #{other}"
  end
end

#-(other) ⇒ Object



44
45
46
# File 'lib/polynomial_ruby/polynomial.rb', line 44

def -(other)
  self + (other * -1)
end

#/(other) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/polynomial_ruby/polynomial.rb', line 48

def /(other)
  if (other.kind_of?(Numeric))
    Polynomial.new(coefficients.map { |c| c / other })
  else
    raise "cannot divide #{self} by #{other}"
  end
end

#==(other) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/polynomial_ruby/polynomial.rb', line 56

def ==(other)
  if (other.kind_of?(self.class))
    coefficients == other.coefficients
  else
    super
  end
end

#degreeObject



13
14
15
# File 'lib/polynomial_ruby/polynomial.rb', line 13

def degree
  coefficients.size - 1
end

#inspectObject



75
76
77
# File 'lib/polynomial_ruby/polynomial.rb', line 75

def inspect
  "#<Polynomial: #{to_s} >"
end

#to_sObject



64
65
66
67
68
69
70
71
72
73
# File 'lib/polynomial_ruby/polynomial.rb', line 64

def to_s
  coefficients[1..-1].reverse.map.with_index { |c, i|
    sign = if (i != 0)
             if (c > 0) then
               "+"
             end
           end
    [sign, "#{c}x^#{degree-i}"].join unless c == 0
  }.push(coefficients[0] != 0 ? "+ #{coefficients[0]}" : nil).compact.join
end