-
Notifications
You must be signed in to change notification settings - Fork 0
/
day13.cr
77 lines (67 loc) · 1.7 KB
/
day13.cr
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
70
71
72
73
74
75
76
77
require "string_scanner"
struct Packet
property :entries
include Comparable(Packet)
def initialize(i = nil)
@entries = Array(Packet | Int32).new
@entries << i if i
end
def <<(value)
@entries << value
end
def <=>(other : Int32)
if entries.size > 0
v = entries.first <=> other
return v if v != 0
entries.size > 1 ? 1 : 0
else
return -1
end
end
def <=>(other)
entries.each_with_index do |e, i|
o = other.is_a?(Packet) ? other.entries[i]? : other
return 1 if o.nil?
v = if e.is_a?(Int32) && o.is_a?(Int32)
e <=> o
elsif e.is_a?(Packet) && o.is_a?(Packet)
e <=> o
elsif e.is_a?(Packet)
e <=> o.as(Int32)
elsif o.is_a?(Packet)
-(o <=> e.as(Int32))
else
raise "unreachable"
end
return v if v != 0
end
other.entries.size > entries.size ? -1 : 0
end
end
def parse(line)
s = StringScanner.new(line)
s.offset += 1
current = Packet.new
stack = [] of Packet
loop do
case s.peek 1
when "["
stack << current
current = Packet.new
stack.last << current
s.offset += 1
when "]"
s.offset += 1
return current if s.eos?
current = stack.pop
when ","
s.offset += 1
else
current << (s.scan /\d+/).not_nil!.to_i
end
end
end
input = File.read_lines("input.day13")
parsed = input.compact_map { |line| line.empty? ? nil : parse(line) }
puts "part1: %s" % parsed.each_slice(2, reuse: true).with_index.sum { |(p1, p2), index| p1 <= p2 ? index + 1 : 0 }
puts "part2: %s" % ((parsed.count(&.<(parse("[[2]]"))) + 1) * (parsed.count(&.<(parse("[[6]]"))) + 2))