-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
123 lines (101 loc) · 1.91 KB
/
main.go
File metadata and controls
123 lines (101 loc) · 1.91 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"github.com/danvolchek/AdventOfCode/lib"
)
func parse(char byte) bool {
return char == '#'
}
type Dir int
const (
North Dir = iota
South
West
East
)
func round(elves *lib.Set[lib.Pos], dirs []Dir) bool {
proposed := make(map[lib.Pos][]lib.Pos)
for _, elf := range elves.Items() {
adjacent := lib.Filter(
lib.AdjacentPosNoBoundsChecks(elf, true),
func(p lib.Pos) bool {
return elves.Contains(p)
},
)
if len(adjacent) == 0 {
continue
}
check := func(pos lib.Pos) bool {
target := elf.Add(pos)
allEmpty := true
for i := -1; i <= 1; i++ {
shouldBeEmpty := target
if pos.Row == 0 {
shouldBeEmpty.Row += i
} else {
shouldBeEmpty.Col += i
}
if elves.Contains(shouldBeEmpty) {
allEmpty = false
break
}
}
if allEmpty {
proposed[target] = append(proposed[target], elf)
}
return allEmpty
}
outer:
for _, dir := range dirs {
switch dir {
case North:
if check(lib.Pos{Row: -1}) {
break outer
}
case South:
if check(lib.Pos{Row: 1}) {
break outer
}
case West:
if check(lib.Pos{Col: -1}) {
break outer
}
case East:
if check(lib.Pos{Col: 1}) {
break outer
}
}
}
}
for pos, proposers := range proposed {
if len(proposers) == 1 {
elves.Remove(proposers[0])
elves.Add(pos)
}
}
return len(proposed) == 0
}
func solve(lines [][]bool) int {
elfMap := &lib.Set[lib.Pos]{}
for y, row := range lines {
for x, hasElf := range row {
if hasElf {
elfMap.Add(lib.Pos{Row: y, Col: x})
}
}
}
dirs := []Dir{North, South, West, East}
i := 1
for !round(elfMap, dirs) {
i++
dirs = append(dirs[1:], dirs[0])
}
return i
}
func main() {
solver := lib.Solver[[][]bool, int]{
ParseF: lib.ParseGrid(parse),
SolveF: solve,
}
solver.Expect("....#..\n..###.#\n#...#.#\n.#...##\n#.###..\n##.#.##\n.#..#..", 20)
solver.Verify(980)
}