|
| 1 | +pub mod util; |
| 2 | +use util::str_to_u32_or_panic; |
| 3 | +use std::cmp::min; |
| 4 | + |
| 5 | +advent_of_code::solution!(3); |
| 6 | + |
| 7 | +pub fn part_one(input: &str) -> Option<u32> { |
| 8 | + let mut numbers = Vec::<String>::new(); |
| 9 | + let vec: Vec<Vec<char>> = input.lines().map(|line| line.chars().collect()).collect(); |
| 10 | + |
| 11 | + let part_number = |nr_str: &str, line: usize, start: usize, end: usize| -> u32 { |
| 12 | + for i in line.saturating_sub(1)..min(line+2, vec.len() - 1) { |
| 13 | + for j in start.saturating_sub(1)..min(end+1, vec[i].len() - 1) { |
| 14 | + if i != line || (j == start.saturating_sub(1) || j == end) { |
| 15 | + let char = vec[i][j]; |
| 16 | + if char != '.' && !char.is_digit(10) { |
| 17 | + return str_to_u32_or_panic(nr_str) |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + 0 |
| 23 | + }; |
| 24 | + |
| 25 | + let mut sum = 0; |
| 26 | + for (i, line) in vec.iter().enumerate() { |
| 27 | + let mut parsing_nr = false; |
| 28 | + for (j, char) in line.iter().enumerate() { |
| 29 | + if char.is_digit(10) { |
| 30 | + if parsing_nr { |
| 31 | + numbers.last_mut().expect("last element should be there") |
| 32 | + .push_str(&char.to_string()); |
| 33 | + } else { |
| 34 | + numbers.push(char.to_string()); |
| 35 | + parsing_nr = true; |
| 36 | + } |
| 37 | + } else { |
| 38 | + if parsing_nr { |
| 39 | + let nr_str = numbers.last().expect("number should be there"); |
| 40 | + sum += part_number(nr_str, i, j - nr_str.len(), j); |
| 41 | + } |
| 42 | + parsing_nr = false; |
| 43 | + } |
| 44 | + } |
| 45 | + if parsing_nr { |
| 46 | + let nr_str = numbers.last().expect("number should be there"); |
| 47 | + sum += part_number(nr_str, i, line.len() - nr_str.len(), line.len()); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + Some(sum) |
| 52 | +} |
| 53 | + |
| 54 | +pub fn part_two(input: &str) -> Option<u32> { |
| 55 | + None |
| 56 | +} |
| 57 | + |
| 58 | +#[cfg(test)] |
| 59 | +mod tests { |
| 60 | + use super::*; |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn test_part_one() { |
| 64 | + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); |
| 65 | + assert_eq!(result, Some(4361)); |
| 66 | + } |
| 67 | + |
| 68 | + #[test] |
| 69 | + fn test_part_two() { |
| 70 | + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); |
| 71 | + assert_eq!(result, None); |
| 72 | + } |
| 73 | +} |
0 commit comments