-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05p1.go
83 lines (67 loc) · 1.56 KB
/
05p1.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
package main
import (
"fmt"
"strings"
"aoc2022/utils"
)
func D05P1() {
lines := utils.ReadLines("./inputs/05.txt")
type move struct {
count int
from int
to int
}
totalStacks := (len(lines[0]) + 1) / 4
var moves []move
var stacks [][]byte
for i := 0; i < totalStacks; i++ {
stacks = append(stacks, []byte{})
}
for i := len(lines) - 1; i >= 0; i-- {
currentLine := lines[i]
// Skip empty lines and stack indexes
if currentLine == "" {
continue
}
if currentLine[1] == '1' {
continue
}
// Parse moves
if strings.Contains(lines[i], "move") {
var currentMove move
fmt.Sscanf(
lines[i],
"move %d from %d to %d",
¤tMove.count,
¤tMove.from,
¤tMove.to,
)
moves = append(moves, currentMove)
continue
}
// Parse crates
for j := 0; j < totalStacks; j++ {
crate := currentLine[(j+1)*4-3]
if crate != ' ' {
stacks[j] = append(stacks[j], crate)
}
}
}
// Loop through moves (in reverse order)
for i := len(moves) - 1; i >= 0; i-- {
currentMove := moves[i]
for i := 0; i < currentMove.count; i++ {
// Pop crate from stack
crate := stacks[currentMove.from-1][len(stacks[currentMove.from-1])-1]
stacks[currentMove.from-1] = stacks[currentMove.from-1][:len(stacks[currentMove.from-1])-1]
// Push crate to stack
stacks[currentMove.to-1] = append(stacks[currentMove.to-1], crate)
}
}
// Get top crates
topCrates := []byte{}
for i := 0; i < totalStacks; i++ {
topCrates = append(topCrates, stacks[i][len(stacks[i])-1])
}
fmt.Println(string(topCrates))
}