advent_of_code_2024/day_11/solution.go

74 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-12-11 09:04:55 +00:00
package day_11
import (
"strconv"
"strings"
)
2024-12-11 09:17:51 +00:00
type Stones map[uint64]uint64
2024-12-11 09:04:55 +00:00
// task:https://adventofcode.com/2024/day/11
func SolveBasic(input string) int {
stones := load(input)
for i := 0; i < 25; i++ {
stones = blink(stones)
}
2024-12-11 09:17:51 +00:00
sum := uint64(0)
for _, st := range stones {
sum += st
}
return int(sum)
2024-12-11 09:04:55 +00:00
}
2024-12-11 09:17:51 +00:00
// task:https://adventofcode.com/2024/day/11#part2
2024-12-11 09:04:55 +00:00
func SolveComplex(input string) int {
2024-12-11 09:17:51 +00:00
stones := load(input)
for i := 0; i < 75; i++ {
stones = blink(stones)
}
sum := uint64(0)
for _, st := range stones {
sum += st
}
return int(sum)
2024-12-11 09:04:55 +00:00
}
2024-12-11 09:17:51 +00:00
func blink(before Stones) Stones {
after := Stones{}
for stone, count := range before {
2024-12-11 09:04:55 +00:00
if stone == 0 {
2024-12-11 09:17:51 +00:00
after[1] += count
2024-12-11 09:04:55 +00:00
} else if val := fromUint(stone); len(val)%2 == 0 {
2024-12-11 09:17:51 +00:00
after[parseUint(val[:len(val)/2])] += count
after[parseUint(val[len(val)/2:])] += count
2024-12-11 09:04:55 +00:00
} else {
2024-12-11 09:17:51 +00:00
after[stone*2024] += count
2024-12-11 09:04:55 +00:00
}
}
return after
}
func fromUint(stone uint64) string {
return strconv.FormatUint(stone, 10)
}
2024-12-11 09:17:51 +00:00
func load(input string) Stones {
stones := Stones{}
2024-12-11 09:04:55 +00:00
for _, substring := range strings.Split(input, " ") {
2024-12-11 09:17:51 +00:00
stones[parseUint(substring)]++
2024-12-11 09:04:55 +00:00
}
return stones
}
func parseUint(substring string) uint64 {
if val, err := strconv.ParseUint(substring, 10, 64); err == nil {
return val
} else {
panic(err)
}
}