Class: Lm::Sum

Inherits:
Object
  • Object
show all
Defined in:
lib/lm/sum.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ Sum

Returns a new instance of Sum.



7
8
9
# File 'lib/lm/sum.rb', line 7

def initialize(str)
  @str = str
end

Instance Attribute Details

#strObject (readonly)

Returns the value of attribute str.



5
6
7
# File 'lib/lm/sum.rb', line 5

def str
  @str
end

Instance Method Details

#by_lengthObject



24
25
26
# File 'lib/lm/sum.rb', line 24

def by_length
  product_list.sort_by(&:length)
end

#multiply(other_sum) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/lm/sum.rb', line 11

def multiply(other_sum)
  raise "Not a sum" unless other_sum.is_a? Sum

  newarr = product_list.map(&:to_a).product(other_sum.product_list.map(&:to_a))

  newstr = newarr.map { |x| x.join("") }.join("+")
  Sum.new(newstr)
end

#product_listObject



20
21
22
# File 'lib/lm/sum.rb', line 20

def product_list
  @str.split("+").map { |x| Set.new(x.split("")) }
end

#reduceObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/lm/sum.rb', line 28

def reduce
  res = []
  arr = by_length

  loop do
    cur = arr.shift

    newarr = []
    arr.each do |x|
      # remove supersets (X + XY = X)
      next if cur.subset?(x)

      newarr << x
    end
    res << cur
    arr = newarr

    break if arr.length.zero?
  end

  Sum.new(res.map { |x| x.to_a.join("") }.join("+"))
end

#to_sObject



51
52
53
# File 'lib/lm/sum.rb', line 51

def to_s
  @str
end