AOC2022/day6/day6.go
2022-12-07 18:17:58 +01:00

48 lines
899 B
Go

package main
import (
"AOC2022/helper"
"fmt"
"os"
)
func main() {
args := os.Args[1:]
lines := helper.ReadTextFile(args[0])
defer helper.MeasureTime("Task One")()
for _, line := range lines {
fmt.Println(getIndexOfFirstNUniqueCharacters(4, line))
fmt.Println(getIndexOfFirstNUniqueCharacters(14, line))
}
}
func getIndexOfFirstNUniqueCharacters(n int, line string) int {
i := 0
fit := false
for !fit && i < len(line) {
firstRepeat := getFirstNRepeat(n, line[i:])
if firstRepeat == -1 {
fit = true
} else {
i += firstRepeat
}
}
return i + n + 1
}
func getFirstNRepeat(n int, line string) int {
usedCharacters := map[string]int{}
for i, character := range line {
if usedCharacters[string(character)] != 0 {
return usedCharacters[string(character)]
}
usedCharacters[string(character)] = i
if len(usedCharacters) == n {
return -1
}
}
return -1
}