AOC2022/day20/day20.go
2022-12-20 19:44:28 +01:00

103 lines
2.6 KiB
Go

package main
import (
"AOC2022/helper"
"fmt"
"os"
)
func main() {
args := os.Args[1:]
lines := helper.ReadTextFile(args[0])
part1(lines)
part2(lines)
}
func part2(lines []string) {
numbers := helper.StringSliceToIntSlice(lines)
numbersWithOriginalIndex := make([][2]int, len(numbers))
for i, number := range numbers {
numbersWithOriginalIndex[i] = [2]int{number * 811589153, i}
}
for j := 0; j < 10; j++ {
for i := 0; i < len(numbers); i++ {
shift(i, &numbersWithOriginalIndex)
}
}
printNumbers := []int{}
currentIndex0 := -1
for i, number := range numbersWithOriginalIndex {
if number[0] == 0 {
currentIndex0 = i
}
printNumbers = append(printNumbers, number[0])
}
sum := 0
iterator := 1000 % len(printNumbers)
for i := 0; i < 3; i++ {
currentIndex0 = (currentIndex0 + iterator) % len(printNumbers)
sum += printNumbers[currentIndex0]
}
fmt.Println(sum)
}
func part1(lines []string) {
numbers := helper.StringSliceToIntSlice(lines)
numbersWithOriginalIndex := make([][2]int, len(numbers))
for i, number := range numbers {
numbersWithOriginalIndex[i] = [2]int{number, i}
}
for i := 0; i < len(numbers); i++ {
shift(i, &numbersWithOriginalIndex)
}
printNumbers := []int{}
currentIndex0 := -1
for i, number := range numbersWithOriginalIndex {
if number[0] == 0 {
currentIndex0 = i
}
printNumbers = append(printNumbers, number[0])
}
fmt.Println(printNumbers)
sum := 0
iterator := 1000 % len(printNumbers)
for i := 0; i < 3; i++ {
currentIndex0 = (currentIndex0 + iterator) % len(printNumbers)
sum += printNumbers[currentIndex0]
}
fmt.Println(sum)
}
func getNthElementAfterN(currentIndex, MoveForward, lengthArray int) int {
remaining := MoveForward % (lengthArray - 1)
newIndex := currentIndex + remaining
if newIndex >= lengthArray {
newIndex = newIndex % (lengthArray - 1)
}
if newIndex <= 0 {
newIndex = lengthArray - 1 + newIndex
}
return newIndex
}
func shift(index int, numbersWithOriginalIndex *[][2]int) {
currentIndex := getNumberWithOriginalIndexN(index, numbersWithOriginalIndex)
currentValue := (*numbersWithOriginalIndex)[currentIndex][0]
move(numbersWithOriginalIndex, currentIndex, currentValue)
}
func move[T any](numbersWithOriginalIndex *[]T, currentIndex int, currentValue int) {
newPosition := getNthElementAfterN(currentIndex, currentValue, len(*numbersWithOriginalIndex))
helper.Move(numbersWithOriginalIndex, currentIndex, newPosition)
}
func getNumberWithOriginalIndexN(index int, numbersWithOriginalIndex *[][2]int) int {
for i, number := range *numbersWithOriginalIndex {
if number[1] == index {
return i
}
}
return -1
}