aboutsummaryrefslogtreecommitdiff
path: root/day24/part2
blob: 84494c293f386db4fcffdf9014be3db84abff6c9 (plain)
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
#!/usr/bin/env ruby

input = $stdin.readlines.map(&:chomp).map{|c| c.split('/').map(&:to_i)}

class BridgeFactory
  def initialize(pieces, bridge = [], be = 0)
    @pieces = pieces.dup
    @bridge = bridge.dup
    @be = be
    @complete = false
  end

  def complete?
    return @complete
  end

  def build_iter
    @complete = true
    nexts = get_nexts
    return nexts.map do |nxt|
      nbe = nxt[0] == nxt[1] ? nxt[0] : (nxt - [@be])[0]
      BridgeFactory.new(@pieces - [nxt], @bridge + [nxt], nbe)
    end
  end

  def strength
    return @bridge.flatten.inject(:+) || 0
  end

  def length
    return @bridge.length
  end

  def to_s
    return "(#{strength})\t\"" + @bridge.map {|p|
      p.join('/')
    }.join('--') + "\""
  end

  private

  def get_nexts
    return @pieces.select do |piece|
      piece[0] == @be || piece[1] == @be
    end
  end
end

bfs = [BridgeFactory.new(input)]

loop do
  new_bfs = []
  bfs.each do |bf|
    if !bf.complete? then
      new_bfs += bf.build_iter
    end
  end
  break if new_bfs.empty?
  bfs = new_bfs
end

puts bfs.map(&:strength).max