Code for the Advent of Code event
aoc
advent-of-code
1#!/usr/bin/env ruby
2# frozen_string_literal: true
3
4require 'digest'
5require 'ostruct'
6
7input = $stdin.readline.strip
8
9def gen(salt, count)
10 Digest::MD5.hexdigest "#{salt}#{count}"
11end
12
13def gen_extra(value)
14 2016.times { value = Digest::MD5.hexdigest value }
15 value
16end
17
18counter = 0
19
20keys = []
21keys2 = []
22
23to_check = {}
24to_check2 = {}
25
26def verify_keys!(to_check, count, key, keys)
27 valid = to_check.select { |c, d| count - c <= 1000 && !d.finished && key =~ d.pattern }
28
29 return if valid.empty?
30
31 valid.each do |c, data|
32 puts "#{data.key} from #{c} matches #{key} at #{count}"
33 data.finished = true
34 keys.push data.key
35 end
36end
37
38def check_match!(key, to_check, count)
39 match = key.match(/([a-z0-9])\1\1/)
40
41 return unless match
42
43 # puts "Found initial hash: #{key}"
44
45 to_check[count] = OpenStruct.new( # rubocop:disable Style/OpenStructUse
46 pattern: /(#{match[1]})\1\1\1\1/, key: key, finished: false
47 )
48end
49
50loop do
51 key = gen input, counter
52 key2 = gen_extra key
53
54 verify_keys! to_check, counter, key, keys
55 verify_keys! to_check2, counter, key2, keys2
56
57 break if keys.size >= 64 && keys2.size >= 64
58
59 check_match! key, to_check, counter
60 check_match! key2, to_check2, counter
61
62 counter += 1
63end
64
65puts "(1) #{to_check.select { |_, d| d.finished }.keys.first(64).max}"
66puts "(2) #{to_check2.select { |_, d| d.finished }.keys.first(64).max}"