Code for the Advent of Code event
aoc
advent-of-code
1#!/usr/bin/env ruby
2# frozen_string_literal: true
3
4TEMPLATE = ARGF.readline.strip
5FIRST, LAST = [TEMPLATE[0], TEMPLATE[-1]]
6PAIRS = TEMPLATE.chars.each_cons(2).tally
7ARGF.readline
8RULES = ARGF.read.scan(/(..) -> (.)/).to_h { [_1.chars, _2] }.freeze
9
10def step(pairs)
11 result = Hash.new(0)
12 pairs.each do |pair, count|
13 if RULES.key? pair
14 char = RULES[pair]
15 result[[pair[0], char]] += count
16 result[[char, pair[1]]] += count
17 else
18 result[pair] += count
19 end
20 end
21 result
22end
23
24def count(pairs)
25 pairs.map { |(a, b), n| [[a, n], [b, n]] }.flatten(1).each_with_object(Hash.new(0)) do |(c, n), h|
26 h[c] += n
27 end.tap do |h|
28 h[FIRST] += 1
29 h[LAST] += 1
30 h.each_key { h[_1] /= 2 }
31 end
32end
33
34puts count(10.times.reduce(PAIRS) { step(_1) }).values.minmax.reverse.reduce(:-) # rubocop:disable Lint/UnexpectedBlockArity
35puts count(40.times.reduce(PAIRS) { step(_1) }).values.minmax.reverse.reduce(:-) # rubocop:disable Lint/UnexpectedBlockArity