-
Notifications
You must be signed in to change notification settings - Fork 0
/
day5.go
65 lines (54 loc) · 1.43 KB
/
day5.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
package main
import (
_ "embed"
"fmt"
"strings"
)
//go:embed input/day5
var d5 string
func day5(input string) (string, string) {
parts := strings.Split(input, "\n\n")
stacks := parseStacks(strings.Split(parts[0], "\n"))
stacksCopy := make([][]string, len(stacks))
copy(stacksCopy, stacks)
return d5impl(parts, stacks, true), d5impl(parts, stacksCopy, false)
}
func d5impl(parts []string, stacks [][]string, moveOneAtTime bool) string {
for _, cmd := range strings.Split(parts[1], "\n") {
var quantity, from, to int
fmt.Sscanf(cmd, "move %d from %d to %d", &quantity, &from, &to)
if moveOneAtTime {
for i := 0; i < quantity; i++ {
stacks[to-1] = append([]string{stacks[from-1][0]}, stacks[to-1]...)
stacks[from-1] = append(stacks[from-1][1:])
}
} else {
if cmd == "" {
break
}
v := make([]string, quantity)
copy(v, stacks[from-1][:quantity])
stacks[to-1] = append(v, stacks[to-1]...)
stacks[from-1] = append(stacks[from-1][quantity:])
}
}
return composeSolution(stacks)
}
func composeSolution(stacks [][]string) string {
var s string
for _, st := range stacks {
s += st[0]
}
return s
}
func parseStacks(startDiagram []string) [][]string {
stacks := make([][]string, len(startDiagram[len(startDiagram)-1])/4+1)
for _, line := range startDiagram {
for idx, c := range line {
if c == int32('[') {
stacks[idx/4] = append(stacks[idx/4], string(line[idx+1]))
}
}
}
return stacks
}