|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + _ "embed" |
| 5 | + "strconv" |
| 6 | + "strings" |
| 7 | +) |
| 8 | + |
| 9 | +//go:embed data.txt |
| 10 | +var fileContents string |
| 11 | + |
| 12 | +func split(number uint64) []uint64 { |
| 13 | + if number == 0 { |
| 14 | + return []uint64{1} |
| 15 | + } |
| 16 | + |
| 17 | + numberStr := strconv.FormatUint(number, 10) |
| 18 | + if len(numberStr)%2 == 0 { |
| 19 | + half := len(numberStr) / 2 |
| 20 | + return []uint64{ |
| 21 | + mustParseUint(numberStr[:half]), |
| 22 | + mustParseUint(numberStr[half:]), |
| 23 | + } |
| 24 | + } |
| 25 | + return []uint64{number * 2024} |
| 26 | +} |
| 27 | + |
| 28 | +func mustParseUint(s string) uint64 { |
| 29 | + num, err := strconv.ParseUint(s, 10, 64) |
| 30 | + if err != nil { |
| 31 | + panic(err) |
| 32 | + } |
| 33 | + return num |
| 34 | +} |
| 35 | + |
| 36 | +func blinking(numbers []uint64, until int) int { |
| 37 | + stones := make(map[uint64]int) |
| 38 | + for _, n := range numbers { |
| 39 | + stones[n]++ |
| 40 | + } |
| 41 | + |
| 42 | + for i := 0; i < until; i++ { |
| 43 | + newStones := make(map[uint64]int) |
| 44 | + |
| 45 | + for n, count := range stones { |
| 46 | + splits := split(n) |
| 47 | + for _, split := range splits { |
| 48 | + newStones[split] += count |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + stones = newStones |
| 53 | + } |
| 54 | + total := 0 |
| 55 | + for _, count := range stones { |
| 56 | + total += count |
| 57 | + } |
| 58 | + return total |
| 59 | + |
| 60 | +} |
| 61 | + |
| 62 | +func main() { |
| 63 | + line := strings.TrimSpace(strings.Split(fileContents, "\n")[0]) |
| 64 | + numbers := make([]uint64, 0) |
| 65 | + for _, numStr := range strings.Fields(line) { |
| 66 | + num := mustParseUint(numStr) |
| 67 | + numbers = append(numbers, num) |
| 68 | + } |
| 69 | + |
| 70 | + total := blinking(numbers, 75) |
| 71 | + println(total) |
| 72 | +} |
0 commit comments