aboutsummaryrefslogtreecommitdiff
path: root/day12/part2
blob: e1af0ed78e5dfe968c1a65e8f80841553adcc9e5 (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
63
64
65
66
67
68
69
#!/usr/bin/env ruby

input = $stdin.readlines.map(&:strip)

is = input[0].split(" ")[2]
rs = input[2..-1]

class Plants
  def initialize(initial_state, rules)
    @state = Hash.new(false)
    parse_state_string(initial_state)
    @rules = []
    parse_rules_lines(rules)
  end

  def step(t = 1)
    t.times do
      newstate = Hash.new(false)

      min = @state.keys.min
      max = @state.keys.max
      ((min-5)..(max+5)).each do |i|
        res = false
        @rules.each do |r|
          ires = true
          (-2..2).each do |o|
            if @state[i + o] != r[o + 2] then
              ires = false
            end
          end
          if ires then
            res = true
          end
        end
        if res then
          newstate[i] = true
        end
      end

      @state = newstate
    end
  end

  def sum
    @state.select { |_, s| s }.keys.sum
  end

  private
  def parse_state_string(state)
    state.chars.each_with_index do |s, i|
      @state[i] = s == "#"
    end
  end

  def parse_rules_lines(rules)
    rules.each do |rule|
      c, r = rule.split(" => ")
      if r == "#" then
        @rules << c.chars.map { |p| p == "#" }
      end
    end
  end
end

m = Plants.new(is, rs)

m.step(50000000000)

puts m.sum