|
| 1 | +module main |
| 2 | + |
| 3 | +import os |
| 4 | +import arrays |
| 5 | + |
| 6 | +const symbols = [`$`, `+`, `@`, `-`, `=`, `*`, `!`, `#`, `&`, `%`, `/`] |
| 7 | + |
| 8 | +fn main() { |
| 9 | + lines := os.read_lines('schematic.input')! |
| 10 | + println('Part 1: ${solve(lines, false)}') |
| 11 | + println('Part 2: ${solve(lines, true)}') |
| 12 | +} |
| 13 | + |
| 14 | +fn solve(lines []string, part_2 bool) int { |
| 15 | + mut coords := [][]int{} |
| 16 | + mut total := 0 |
| 17 | + for i := 0; i < lines.len; i++ { |
| 18 | + for j := 0; j < lines[i].len; j++ { |
| 19 | + if lines[i][j] in symbols { |
| 20 | + mut temp := []int{} |
| 21 | + temp << explore(lines, i - 1, j - 1) |
| 22 | + temp << explore(lines, i - 1, j) |
| 23 | + temp << explore(lines, i - 1, j + 1) |
| 24 | + temp << explore(lines, i, j - 1) |
| 25 | + temp << explore(lines, i, j + 1) |
| 26 | + temp << explore(lines, i + 1, j - 1) |
| 27 | + temp << explore(lines, i + 1, j) |
| 28 | + temp << explore(lines, i + 1, j + 1) |
| 29 | + coords << arrays.uniq(temp.filter(it != 0)) |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + if part_2 { |
| 34 | + for line in coords.filter(it.len == 2) { |
| 35 | + total += line[0] * line[1] |
| 36 | + } |
| 37 | + } else { |
| 38 | + for line in coords { |
| 39 | + total += arrays.sum[int](line) or { panic(err) } |
| 40 | + } |
| 41 | + } |
| 42 | + return total |
| 43 | +} |
| 44 | + |
| 45 | +fn explore(lines []string, row int, col int) int { |
| 46 | + lines[row] or { return 0 }.substr_with_check(col, col) or { return 0 } |
| 47 | + if lines[row][col] == `.` { |
| 48 | + return 0 |
| 49 | + } |
| 50 | + mut beg := col |
| 51 | + mut end := col |
| 52 | + for beg > 0 { |
| 53 | + if lines[row][beg - 1] == `.` || lines[row][beg - 1] in symbols { |
| 54 | + break |
| 55 | + } |
| 56 | + beg -= 1 |
| 57 | + } |
| 58 | + for end < lines[row].len - 1 { |
| 59 | + if lines[row][end + 1] == `.` || lines[row][end + 1] in symbols { |
| 60 | + break |
| 61 | + } |
| 62 | + end += 1 |
| 63 | + } |
| 64 | + return lines[row].substr(beg, end + 1).int() |
| 65 | +} |
0 commit comments