|
| 1 | +use crate::util::grid::*; |
| 2 | +use crate::util::parse::*; |
| 3 | +use crate::util::point::*; |
| 4 | + |
| 5 | +pub fn parse(input: &str) -> &str { |
| 6 | + input |
| 7 | +} |
| 8 | + |
| 9 | +pub fn part1(input: &str) -> u64 { |
| 10 | + let lines: Vec<_> = input.lines().rev().collect(); |
| 11 | + let operations: Vec<_> = lines[0].split_ascii_whitespace().collect(); |
| 12 | + let numbers: Vec<Vec<u64>> = |
| 13 | + lines[1..].iter().map(|line| line.iter_unsigned().collect()).collect(); |
| 14 | + |
| 15 | + operations |
| 16 | + .into_iter() |
| 17 | + .enumerate() |
| 18 | + .map(|(col, operation)| match operation { |
| 19 | + "+" => numbers.iter().map(|row| row[col]).sum::<u64>(), |
| 20 | + "*" => numbers.iter().map(|row| row[col]).product::<u64>(), |
| 21 | + _ => unreachable!(), |
| 22 | + }) |
| 23 | + .sum() |
| 24 | +} |
| 25 | + |
| 26 | +pub fn part2(input: &str) -> u64 { |
| 27 | + let grid = Grid::parse(input); |
| 28 | + let top = grid.height - 1; |
| 29 | + |
| 30 | + let mut total = 0; |
| 31 | + let mut start = 0; |
| 32 | + let mut column = Vec::new(); |
| 33 | + |
| 34 | + while start < grid.width { |
| 35 | + let mut end = start + 1; |
| 36 | + while end < grid.width && grid[Point::new(end, top)] == b' ' { |
| 37 | + end += 1; |
| 38 | + } |
| 39 | + if end < grid.width { |
| 40 | + end -= 1; |
| 41 | + } |
| 42 | + |
| 43 | + for x in start..end { |
| 44 | + let mut number = 0; |
| 45 | + |
| 46 | + for y in 0..top { |
| 47 | + let point = Point::new(x, y); |
| 48 | + if grid[point] != b' ' { |
| 49 | + number = 10 * number + (grid[point] - b'0') as u64; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + column.push(number); |
| 54 | + } |
| 55 | + |
| 56 | + total += match grid[Point::new(start, top)] { |
| 57 | + b'+' => column.iter().sum::<u64>(), |
| 58 | + b'*' => column.iter().product::<u64>(), |
| 59 | + _ => unreachable!(), |
| 60 | + }; |
| 61 | + start = end + 1; |
| 62 | + column.clear(); |
| 63 | + } |
| 64 | + |
| 65 | + total |
| 66 | +} |
0 commit comments