-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday24.jl
More file actions
104 lines (93 loc) · 2.71 KB
/
day24.jl
File metadata and controls
104 lines (93 loc) · 2.71 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
module Day24
using AdventOfCode2020
function day24(input::String = readInput(joinpath(@__DIR__, "..", "data", "day24.txt")))
lines = split(input)
return solve(lines)
end
function solve(lines)
# Uses cube coordinates
# Reference: https://www.redblobgames.com/grids/hexagons/
tiles = Array{Array{Int,1},1}()
for line in lines
coordinates = [0, 0, 0]
i = 1
while i <= length(line)
if line[i] == 'e'
coordinates[1:2] += [1, -1]
elseif line[i] == 'w'
coordinates[1:2] += [-1, 1]
elseif line[i] == 'n'
i += 1
if line[i] == 'e'
coordinates[1] += 1
coordinates[3] -= 1
elseif line[i] == 'w'
coordinates[2] += 1
coordinates[3] -= 1
end
elseif line[i] == 's'
i += 1
if line[i] == 'e'
coordinates[2] -= 1
coordinates[3] += 1
elseif line[i] == 'w'
coordinates[1] -= 1
coordinates[3] += 1
end
end
i += 1
end
push!(tiles, coordinates)
end
d = Dict{Array{Int,1},Bool}()
for tile in tiles
color = get(d, tile, false)
d[tile] = !color
end
black_tiles = Set{Tuple{Int,Int,Int}}()
for (k, v) in d
if v
push!(black_tiles, Tuple(k))
end
end
p1 = length(black_tiles)
for day = 1:100
remove = Set{Tuple{Int,Int,Int}}()
add = Set{Tuple{Int,Int,Int}}()
for tile in black_tiles
neighbours = neighbour_coordinates(tile)
for coord in [tile, neighbours...]
n2 = neighbour_coordinates(coord)
c = sum(neigh ∈ black_tiles for neigh in n2)
if coord ∈ black_tiles # black
if c == 0 || c > 2
push!(remove, coord)
end
else # white
if c == 2
push!(add, coord)
end
end
end
end
# Update black tiles:
for coord in remove
delete!(black_tiles, coord)
end
for coord in add
push!(black_tiles, coord)
end
end
return [p1, length(black_tiles)]
end
function neighbour_coordinates(source::Tuple{Int,Int,Int})
return (
source .+ (1, -1, 0),
source .+ (0, -1, 1),
source .+ (-1, 0, 1),
source .+ (-1, 1, 0),
source .+ (0, 1, -1),
source .+ (1, 0, -1)
)
end
end # module