|
| 1 | +import os |
| 2 | +import math |
| 3 | + |
| 4 | +fn main() { |
| 5 | + original_stones := os.read_file('stones.input')!.split(' ').map(it.i64()) |
| 6 | + mut stones := original_stones.clone() |
| 7 | + |
| 8 | + for _ in 0 .. 25 { |
| 9 | + mut new_stones := []i64{cap: stones.len * 2} |
| 10 | + for stone in stones { |
| 11 | + if stone == 0 { |
| 12 | + new_stones << 1 |
| 13 | + } else { |
| 14 | + digits := if stone == 10 { 1 } else { int(math.log10(stone)) } |
| 15 | + if digits % 2 == 1 { |
| 16 | + power := i64(math.pow(10, digits / 2 + 1)) |
| 17 | + new_stones << stone / power |
| 18 | + new_stones << stone % power |
| 19 | + } else { |
| 20 | + new_stones << stone * 2024 |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + stones = unsafe { new_stones } |
| 26 | + } |
| 27 | + |
| 28 | + println('part1: ${stones.len}') |
| 29 | + |
| 30 | + mut total := i64(0) |
| 31 | + mut b := Bruteforcer{} |
| 32 | + for stone in original_stones { |
| 33 | + total += b.force(stone, 75) |
| 34 | + } |
| 35 | + |
| 36 | + println('part2: ${total}') |
| 37 | +} |
| 38 | + |
| 39 | +struct Bruteforcer { |
| 40 | +mut: |
| 41 | + cache map[string]i64 |
| 42 | +} |
| 43 | + |
| 44 | +fn (mut b Bruteforcer) force(stone i64, rem int) i64 { |
| 45 | + cache_key := '${stone},${rem}' |
| 46 | + if cached := b.cache[cache_key] { |
| 47 | + return cached |
| 48 | + } |
| 49 | + |
| 50 | + if rem == 0 { |
| 51 | + return 1 |
| 52 | + } |
| 53 | + |
| 54 | + mut total := i64(0) |
| 55 | + if stone == 0 { |
| 56 | + total = b.force(1, rem - 1) |
| 57 | + } else { |
| 58 | + // math.log10(10) is 0.9999999999 and rounds down to 0.... |
| 59 | + digits := if stone == 10 { 1 } else { int(math.log10(stone)) } |
| 60 | + if digits % 2 == 1 { |
| 61 | + power := i64(math.pow(10, digits / 2 + 1)) |
| 62 | + total = b.force(stone / power, rem - 1) + b.force(stone % power, rem - 1) |
| 63 | + } else { |
| 64 | + total = b.force(stone * 2024, rem - 1) |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + b.cache[cache_key] = total |
| 69 | + return total |
| 70 | +} |
0 commit comments