|
| 1 | +pub fn part1(contents: &str) -> i64 { |
| 2 | + let split_lines: Vec<Vec<&str>> = contents |
| 3 | + .lines() |
| 4 | + .map(|line| line.split_whitespace().collect()) |
| 5 | + .collect(); |
| 6 | + |
| 7 | + let mut parsed_input = Vec::new(); |
| 8 | + for i in 0..split_lines[0].len() { |
| 9 | + let mut column = Vec::new(); |
| 10 | + for j in 0..split_lines.len() - 1 { |
| 11 | + let cell = &split_lines[j][i]; |
| 12 | + column.push(cell.parse::<i64>().unwrap()); |
| 13 | + } |
| 14 | + parsed_input.push(( |
| 15 | + column, |
| 16 | + split_lines[split_lines.len() - 1][i] |
| 17 | + .chars() |
| 18 | + .next() |
| 19 | + .unwrap(), |
| 20 | + )); |
| 21 | + } |
| 22 | + |
| 23 | + let mut result = 0; |
| 24 | + for (column, operation) in parsed_input { |
| 25 | + match operation { |
| 26 | + '+' => result += column.iter().sum::<i64>(), |
| 27 | + '*' => result += column.iter().product::<i64>(), |
| 28 | + _ => panic!("Unknown operation"), |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + result |
| 33 | +} |
| 34 | + |
| 35 | +pub fn part2(contents: &str) -> i64 { |
| 36 | + let lines: Vec<Vec<char>> = contents |
| 37 | + .lines() |
| 38 | + .map(|line| line.chars().collect()) |
| 39 | + .collect(); |
| 40 | + |
| 41 | + let mut result = 0; |
| 42 | + let mut numbers = Vec::new(); |
| 43 | + |
| 44 | + for i in (0..lines[0].len()).rev() { |
| 45 | + let mut found_number = false; |
| 46 | + let mut number = 0; |
| 47 | + let mut multiplier = 1; |
| 48 | + |
| 49 | + for j in (0..lines.len() - 1).rev() { |
| 50 | + if lines[j][i] == ' ' { |
| 51 | + continue; |
| 52 | + } |
| 53 | + found_number = true; |
| 54 | + number += (lines[j][i].to_digit(10).unwrap() as i64) * multiplier; |
| 55 | + multiplier *= 10; |
| 56 | + } |
| 57 | + |
| 58 | + if found_number { |
| 59 | + numbers.push(number); |
| 60 | + } |
| 61 | + |
| 62 | + if lines[lines.len() - 1][i] != ' ' { |
| 63 | + match lines[lines.len() - 1][i] { |
| 64 | + '+' => result += numbers.iter().sum::<i64>(), |
| 65 | + '*' => result += numbers.iter().product::<i64>(), |
| 66 | + _ => panic!("Unknown operation"), |
| 67 | + } |
| 68 | + numbers.clear(); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + result |
| 73 | +} |
| 74 | + |
| 75 | +#[cfg(test)] |
| 76 | +mod tests { |
| 77 | + use super::*; |
| 78 | + |
| 79 | + #[test] |
| 80 | + fn test_part1() { |
| 81 | + let input = vec![ |
| 82 | + "123 328 51 64 ", |
| 83 | + " 45 64 387 23 ", |
| 84 | + " 6 98 215 314", |
| 85 | + "* + * + ", |
| 86 | + ]; |
| 87 | + |
| 88 | + assert_eq!(part1(&input.join("\n")), 4277556); |
| 89 | + } |
| 90 | + |
| 91 | + #[test] |
| 92 | + fn test_part2() { |
| 93 | + let input = vec![ |
| 94 | + "123 328 51 64 ", |
| 95 | + " 45 64 387 23 ", |
| 96 | + " 6 98 215 314", |
| 97 | + "* + * + ", |
| 98 | + ]; |
| 99 | + |
| 100 | + assert_eq!(part2(&input.join("\n")), 3263827); |
| 101 | + } |
| 102 | +} |
0 commit comments