AOC2022/day13/day13.go

116 lines
2.2 KiB
Go
Raw Normal View History

2022-12-13 20:45:45 +01:00
package main
import (
"AOC2022/helper"
"fmt"
"strconv"
)
func main() {
//args := os.Args[1:]
lines := helper.ReadTextFile("day13/testinput")
result := 0
index := 1
for i := 18; i < len(lines); i += 3 {
fmt.Println(i)
if comparePair(lines[i], lines[i+1]) {
result += index
}
index++
}
fmt.Println(result)
}
func comparePair(left string, right string) bool {
lefIndex := 0
rightIndex := 0
currentElemLeft := 0
currentElemRight := 0
for lefIndex < len(left)-1 {
lefIndex = getNextElement(left, lefIndex)
if left[lefIndex] == ']' {
lefIndex = getNextElement(left, lefIndex+1)
rightIndex = getEndofCurrentArray(right, rightIndex)
rightIndex = getNextElement(right, rightIndex+1)
} else {
rightIndex = getNextElement(right, rightIndex)
if rightIndex == -1 {
return false
}
if lefIndex == -1 {
return true
}
currentElemLeft, lefIndex = readElement(left, lefIndex)
currentElemRight, rightIndex = readElement(right, rightIndex)
fmt.Println(currentElemLeft)
fmt.Println(currentElemRight)
fmt.Println()
if currentElemLeft > currentElemRight {
return false
}
if currentElemLeft < currentElemRight {
return true
}
}
}
return true
}
// 0 Element
//-1 End Packet
//-2 Start Array
//-3 End Array
func getNextElement(packet string, currentIndex int) (int, int) {
index := currentIndex
for index < len(packet) {
switch packet[index] {
case ',':
index++
break
case '[':
return index, -2
break
case ']':
if index < len(packet)-1 {
return index, -3
} else {
index++
}
break
default:
return index, 0
}
}
return index, -1
}
func getEndofCurrentArray(packet string, currentIndex int) int {
index := currentIndex
for index < len(packet) {
if packet[index] == ']' {
return index
}
index++
}
return -1
}
func readElement(packet string, currentIndex int) (element, newIndex int) {
index := currentIndex
newIndex = 0
for newIndex == 0 {
switch packet[index] {
case ',':
newIndex = index
break
case ']':
newIndex = index
break
default:
index++
}
}
return helper.RemoveError(strconv.Atoi(packet[currentIndex:newIndex])), newIndex
}