|
| 1 | +module main |
| 2 | + |
| 3 | +import arrays |
| 4 | +import os |
| 5 | + |
| 6 | +const digits = '0123456789'.runes() |
| 7 | + |
| 8 | +fn main() { |
| 9 | + lines := os.read_lines('schematic.input')! |
| 10 | + |
| 11 | + width := lines[0].len + 2 |
| 12 | + deltas := [ |
| 13 | + -width - 1, |
| 14 | + -width, |
| 15 | + -width + 1, |
| 16 | + -1, |
| 17 | + 1, |
| 18 | + width - 1, |
| 19 | + width, |
| 20 | + width + 1, |
| 21 | + ] |
| 22 | + |
| 23 | + extra_row := '.'.repeat(width) |
| 24 | + mut padded := [extra_row] |
| 25 | + padded << lines.map('.${it}.') |
| 26 | + padded << extra_row |
| 27 | + |
| 28 | + grid := arrays.flatten(padded.map(it.runes())) |
| 29 | + |
| 30 | + mut part_one := 0 |
| 31 | + |
| 32 | + mut digit := '' |
| 33 | + mut digit_indices := []int{} |
| 34 | + mut gears := map[int][]int{} |
| 35 | + for idx, chr in grid { |
| 36 | + if chr in digits { |
| 37 | + digit += chr.str() |
| 38 | + digit_indices << idx |
| 39 | + continue |
| 40 | + } |
| 41 | + |
| 42 | + if digit.len > 0 { |
| 43 | + digit_value := digit.int() |
| 44 | + if is_part(digit_indices, digit_value, grid, deltas, mut gears) { |
| 45 | + part_one += digit_value |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + digit = '' |
| 50 | + digit_indices = [] |
| 51 | + } |
| 52 | + |
| 53 | + part_two := arrays.sum(gears |
| 54 | + .keys() |
| 55 | + .filter(gears[it].len == 2) |
| 56 | + .map(arrays.reduce(gears[it], fn (a int, b int) int { |
| 57 | + return a * b |
| 58 | + })!))! |
| 59 | + |
| 60 | + println('Part 1: ${part_one}') |
| 61 | + println('Part 2: ${part_two}') |
| 62 | +} |
| 63 | + |
| 64 | +fn is_part(digit_indices []int, digit_value int, grid []rune, deltas []int, mut gears map[int][]int) bool { |
| 65 | + neighbours := digit_indices.map(fn [deltas] (i int) []int { |
| 66 | + return deltas.map(i + it) |
| 67 | + }) |
| 68 | + |
| 69 | + mut result := false |
| 70 | + for idx in arrays.map_of_indexes[int](arrays.flatten(neighbours)).keys() { |
| 71 | + chr := grid[idx] |
| 72 | + if chr == `.` || chr in digits { |
| 73 | + continue |
| 74 | + } else if chr == `*` { |
| 75 | + gears[idx] << digit_value |
| 76 | + } |
| 77 | + result = true |
| 78 | + } |
| 79 | + |
| 80 | + return result |
| 81 | +} |
0 commit comments