-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
108 lines (84 loc) · 1.84 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
package main
import (
"bufio"
"fmt"
"io"
"os"
"path"
"strings"
)
func input() *os.File {
input, err := os.Open(path.Join("2021", "25", "input.txt"))
if err != nil {
panic(err)
}
return input
}
func solve(r io.Reader) {
scanner := bufio.NewScanner(r)
var cucumbers [][]byte
for scanner.Scan() {
line := scanner.Text()
row := make([]byte, len(line))
for i := range row {
row[i] = line[i]
}
cucumbers = append(cucumbers, row)
}
if scanner.Err() != nil {
panic(scanner.Err())
}
i := 0
for move(cucumbers) {
i += 1
}
fmt.Println(i)
}
type pos struct{ i, j int }
type swap struct{ p1, p2 pos }
func move(cucumbers [][]byte) bool {
moved := false
var swaps []swap
for i := 0; i < len(cucumbers); i++ {
for j := 0; j < len(cucumbers[i]); j++ {
if cucumbers[i][j] != '>' {
continue
}
nextJ := j + 1
if nextJ == len(cucumbers[i]) {
nextJ = 0
}
if cucumbers[i][nextJ] == '.' {
moved = true
swaps = append(swaps, swap{p1: pos{i, j}, p2: pos{i, nextJ}})
}
}
}
for _, sw := range swaps {
cucumbers[sw.p1.i][sw.p1.j], cucumbers[sw.p2.i][sw.p2.j] = cucumbers[sw.p2.i][sw.p2.j], cucumbers[sw.p1.i][sw.p1.j]
}
swaps = nil
for i := 0; i < len(cucumbers); i++ {
for j := 0; j < len(cucumbers[i]); j++ {
if cucumbers[i][j] != 'v' {
continue
}
nextI := i + 1
if nextI == len(cucumbers) {
nextI = 0
}
if cucumbers[nextI][j] == '.' {
moved = true
swaps = append(swaps, swap{p1: pos{i, j}, p2: pos{nextI, j}})
}
}
}
for _, sw := range swaps {
cucumbers[sw.p1.i][sw.p1.j], cucumbers[sw.p2.i][sw.p2.j] = cucumbers[sw.p2.i][sw.p2.j], cucumbers[sw.p1.i][sw.p1.j]
}
return moved
}
func main() {
solve(strings.NewReader("v...>>.vv>\n.vv>>.vv..\n>>.>v>...v\n>>v>>.>.v.\nv>v.vv.v..\n>.>>..v...\n.vv..>.>v.\nv.v..>>v.v\n....v..v.>"))
solve(input())
}