-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
129 lines (103 loc) · 2.34 KB
/
main.go
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
124
125
126
127
128
129
package main
import (
"github.com/danvolchek/AdventOfCode/lib"
"regexp"
"strings"
)
type stack[T any] struct {
items []T
}
func (s *stack[T]) Push(item T) {
s.items = append(s.items, item)
}
func (s *stack[T]) Empty() bool {
return len(s.items) == 0
}
func (s *stack[T]) Pop() T {
if s.Empty() {
panic("empty")
}
item := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return item
}
func (s *stack[T]) Top() T {
return s.items[len(s.items)-1]
}
func (s *stack[T]) Reverse() {
var items []T
for !s.Empty() {
items = append(items, s.Pop())
}
s.items = items
}
type instruction struct {
amount, from, to int
}
type puzzle struct {
stacks []*stack[string]
instructions []instruction
}
func parse(inp string) puzzle {
doingInstructs := false
stacks := []*stack[string]{{}, {}, {}}
var p puzzle
for _, line := range strings.Split(inp, "\n") {
if line == "" {
doingInstructs = true
continue
}
switch doingInstructs {
case true:
reg := regexp.MustCompile(`move (\d+) from (\d+) to (\d+)`)
matches := reg.FindAllStringSubmatch(line, -1)
firstMatchSubmatches := matches[0][1:]
p.instructions = append(p.instructions, instruction{
amount: lib.Atoi(firstMatchSubmatches[0]),
from: lib.Atoi(firstMatchSubmatches[1]) - 1,
to: lib.Atoi(firstMatchSubmatches[2]) - 1,
})
case false:
for i := 0; i < len(line); i++ {
if line[i] >= 'A' && line[i] <= 'Z' {
targ := (i - 1) / 4
for len(stacks) < targ+1 {
stacks = append(stacks, &stack[string]{})
}
stacks[(i-1)/4].Push(string(line[i]))
}
}
}
}
for _, stack := range stacks {
stack.Reverse()
}
return puzzle{
stacks: stacks,
instructions: p.instructions,
}
}
func solve(puzz puzzle) string {
for _, instr := range puzz.instructions {
temp := &stack[string]{}
for i := 0; i < instr.amount; i++ {
temp.Push(puzz.stacks[instr.from].Pop())
}
for i := 0; i < instr.amount; i++ {
puzz.stacks[instr.to].Push(temp.Pop())
}
}
ret := ""
for _, s := range puzz.stacks {
ret += s.Top()
}
return ret
}
func main() {
solver := lib.Solver[puzzle, string]{
ParseF: parse,
SolveF: solve,
}
solver.Expect(" [D] \n[N] [C] \n[Z] [M] [P]\n 1 2 3 \n\nmove 1 from 2 to 1\nmove 3 from 1 to 3\nmove 2 from 2 to 1\nmove 1 from 1 to 2", "MCD")
solver.Verify("LCTQFBVZV")
}