|
| 1 | +use crate::util::grid::*; |
| 2 | +use crate::util::point::*; |
| 3 | + |
| 4 | +type Input = (u64, u64); |
| 5 | + |
| 6 | +pub fn parse(input: &str) -> Input { |
| 7 | + let grid = Grid::parse(input); |
| 8 | + let bottom = grid.height - 1; |
| 9 | + let mut right = grid.width; |
| 10 | + |
| 11 | + (0..grid.width).rev().filter(|&x| grid[Point::new(x, bottom)] != b' ').fold( |
| 12 | + (0, 0), |
| 13 | + |(part_one, part_two), left| { |
| 14 | + let rows = (0..bottom).map(|y| (left..right).fold(0, |num, x| acc(&grid, num, x, y))); |
| 15 | + let cols = (left..right).map(|x| (0..bottom).fold(0, |num, y| acc(&grid, num, x, y))); |
| 16 | + |
| 17 | + let plus = grid[Point::new(left, bottom)] == b'+'; |
| 18 | + let first: u64 = if plus { rows.sum() } else { rows.product() }; |
| 19 | + let second: u64 = if plus { cols.sum() } else { cols.product() }; |
| 20 | + |
| 21 | + right = left - 1; |
| 22 | + (part_one + first, part_two + second) |
| 23 | + }, |
| 24 | + ) |
| 25 | +} |
| 26 | + |
| 27 | +pub fn part1(input: &Input) -> u64 { |
| 28 | + input.0 |
| 29 | +} |
| 30 | + |
| 31 | +pub fn part2(input: &Input) -> u64 { |
| 32 | + input.1 |
| 33 | +} |
| 34 | + |
| 35 | +fn acc(grid: &Grid<u8>, number: u64, x: i32, y: i32) -> u64 { |
| 36 | + let digit = grid[Point::new(x, y)]; |
| 37 | + if digit == b' ' { number } else { 10 * number + (digit - b'0') as u64 } |
| 38 | +} |
0 commit comments