-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday3.cr
58 lines (51 loc) · 1.33 KB
/
day3.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
def check(pos, v, symbols, connectors)
if symbols.includes?(pos)
connectors[pos] ||= [] of Int32
connectors[pos] << v
true
end
end
def row_check(x, y, size, v, symbols, connectors)
((y - 1)..(y + size)).each do |y|
if check({x - 1, y}, v, symbols, connectors) || check({x + 1, y}, v, symbols, connectors)
return true
end
end
end
def read_number(seen, pos, char, numbers)
x, y = pos
v = char.to_i
size = 1
while c = numbers[{x, y + 1}]?
size += 1
y += 1
v *= 10
v += c.to_i
seen << {x, y}
end
{v, size}
end
numbers = Hash(Tuple(Int32, Int32), Char).new
symbols = Set(Tuple(Int32, Int32)).new
File.read("input.day3").each_line.with_index do |line, i|
line.each_char.with_index do |c, j|
if c == '.'
elsif c.number?
numbers[{i, j}] = c
else
symbols << {i, j}
end
end
end
connectors = Hash(Tuple(Int32, Int32), Array(Int32)).new
seen = Set(Tuple(Int32, Int32)).new
numbers.each do |pos, char|
next if seen.includes?(pos)
v, size = read_number(seen, pos, char, numbers)
x, y = pos
row_check(x, y, size, v, symbols, connectors) ||
check({x, y - 1}, v, symbols, connectors) ||
check({x, y + size}, v, symbols, connectors)
end
puts "part1: %s" % connectors.sum &.last.sum
puts "part2: %s" % connectors.sum { |_, v| v.size == 2 ? v.product : 0 }