This commit is contained in:
Stefan Harmuth 2021-01-13 22:44:02 +01:00
parent f0a0aa306a
commit d2419e32a6

View File

@ -1,13 +1,13 @@
package day04 package day04
import ( import (
"fmt"
"regexp" "regexp"
"sort"
"strconv" "strconv"
"tools" "tools"
) )
var roomRegexp = regexp.MustCompile(`^(.*)-([[:digit:]]+)\[(.*)\]$`) var roomRegexp = regexp.MustCompile(`^(.*)-([[:digit:]]+)\[(.*)]$`)
func validateChecksum(roomname, checksum string) bool { func validateChecksum(roomname, checksum string) bool {
charcount := make(map[int32]int) charcount := make(map[int32]int)
@ -16,31 +16,71 @@ func validateChecksum(roomname, checksum string) bool {
charcount[c]++ charcount[c]++
} }
} }
for i, c := range checksum {
if i == 0 { charcountReverse := make(map[int]tools.ByteSlice)
continue counts := tools.NewSetInt()
} for c, v := range charcount {
if c < int32(checksum[i-1]) || charcount[c] > charcount[int32(checksum[i-1])] { counts.Add(v)
return false charcountReverse[v] = append(charcountReverse[v], byte(c))
}
countList := counts.Keys()
sort.Sort(sort.Reverse(countList))
calcChecksum := ""
for _, v := range countList {
charList := charcountReverse[v]
sort.Sort(charList)
for _, c := range charList {
calcChecksum += string(c)
} }
} }
return true
return checksum == calcChecksum[:5]
} }
func Part1(puzzle tools.AoCPuzzle) interface{} { func Part1(puzzle tools.AoCPuzzle) interface{} {
sectorSum := 0
for _, line := range puzzle.GetInputArray() { for _, line := range puzzle.GetInputArray() {
roomMatches := roomRegexp.FindStringSubmatch(line) roomMatches := roomRegexp.FindStringSubmatch(line)
roomName := roomMatches[1] roomName := roomMatches[1]
roomSectorId, _ := strconv.Atoi(roomMatches[2]) roomSectorId, _ := strconv.Atoi(roomMatches[2])
roomChecksum := roomMatches[3] roomChecksum := roomMatches[3]
fmt.Println("Name:", roomName, "SectorID:", roomSectorId, "CheckSum:", roomChecksum)
if !validateChecksum(roomName, roomChecksum) { if validateChecksum(roomName, roomChecksum) {
fmt.Println("MEEP!") sectorSum += roomSectorId
} }
} }
return 0
return sectorSum
} }
func Part2(puzzle tools.AoCPuzzle) interface{} { func Part2(puzzle tools.AoCPuzzle) interface{} {
return 0 for _, line := range puzzle.GetInputArray() {
roomMatches := roomRegexp.FindStringSubmatch(line)
roomName := roomMatches[1]
roomSectorId, _ := strconv.Atoi(roomMatches[2])
roomChecksum := roomMatches[3]
if validateChecksum(roomName, roomChecksum) {
addNum := int32(roomSectorId) % 26
realName := ""
for _, c := range roomName {
switch c {
case '-':
realName += " "
default:
for c+addNum > 122 {
c -= 26
}
realName += string(c + addNum)
}
}
if realName == "northpole object storage" {
return roomSectorId
}
}
}
return -1
} }