2022 Day 20 Complete!
This commit is contained in:
101
2022/day20/main.go
Normal file
101
2022/day20/main.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
h "git.bullercodeworks.com/brian/adventofcode/helpers"
|
||||
)
|
||||
|
||||
type Node struct {
|
||||
value int
|
||||
prev *Node
|
||||
next *Node
|
||||
}
|
||||
|
||||
func main() {
|
||||
inp := h.StdinToStringSlice()
|
||||
part1(inp)
|
||||
part2(inp)
|
||||
}
|
||||
|
||||
func part1(inp []string) {
|
||||
var list []*Node
|
||||
var first *Node
|
||||
for i := range inp {
|
||||
n := &Node{value: h.Atoi(inp[i])}
|
||||
if n.value == 0 {
|
||||
first = n
|
||||
}
|
||||
list = append(list, n)
|
||||
}
|
||||
initList(list)
|
||||
mixAll(list)
|
||||
fmt.Println("# Part 1")
|
||||
fmt.Println(getCoords(first))
|
||||
}
|
||||
|
||||
func part2(inp []string) {
|
||||
key := 811589153
|
||||
var list []*Node
|
||||
var first *Node
|
||||
for i := range inp {
|
||||
n := &Node{value: h.Atoi(inp[i]) * key}
|
||||
if n.value == 0 {
|
||||
first = n
|
||||
}
|
||||
list = append(list, n)
|
||||
}
|
||||
initList(list)
|
||||
for i := 0; i < 10; i++ {
|
||||
mixAll(list)
|
||||
}
|
||||
fmt.Println("# Part 2")
|
||||
fmt.Println(getCoords(first))
|
||||
}
|
||||
|
||||
func initList(list []*Node) {
|
||||
list[0].prev = list[len(list)-1]
|
||||
list[len(list)-1].next = list[0]
|
||||
for i := 1; i < len(list); i++ {
|
||||
list[i].prev = list[i-1]
|
||||
list[i-1].next = list[i]
|
||||
}
|
||||
}
|
||||
|
||||
func move(n *Node, count int) *Node {
|
||||
for count < 0 {
|
||||
n = n.prev
|
||||
count++
|
||||
}
|
||||
for count > 0 {
|
||||
n = n.next
|
||||
count--
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func mix(n *Node, listLen int) {
|
||||
t := n.prev
|
||||
n.prev.next = n.next
|
||||
n.next.prev = n.prev
|
||||
t = move(t, n.value%(listLen-1))
|
||||
n.prev = t
|
||||
n.next = t.next
|
||||
n.prev.next = n
|
||||
n.next.prev = n
|
||||
}
|
||||
|
||||
func mixAll(list []*Node) {
|
||||
for _, n := range list {
|
||||
mix(n, len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func getCoords(first *Node) int {
|
||||
var res int
|
||||
for i, n := 0, first; i < 3; i++ {
|
||||
n = move(n, 1000)
|
||||
res += n.value
|
||||
}
|
||||
return res
|
||||
}
|
||||
Reference in New Issue
Block a user