diff --git a/data/examples/06.txt b/data/examples/06.txt new file mode 100644 index 0000000..d974a3a --- /dev/null +++ b/data/examples/06.txt @@ -0,0 +1,4 @@ +123 328 51 64 + 45 64 387 23 + 6 98 215 314 +* + * + diff --git a/src/bin/06.rs b/src/bin/06.rs new file mode 100644 index 0000000..a8b2a69 --- /dev/null +++ b/src/bin/06.rs @@ -0,0 +1,102 @@ +use itertools::Itertools; + +advent_of_code::solution!(6); + +pub fn part_one(input: &str) -> Option { + let number_rows = input + .lines() + .filter(|line| { + !line.is_empty() && line.chars().find(|c| *c != ' ').unwrap_or(' ').is_numeric() + }) + .map(|line| { + line.split(" ") + .filter(|s| !s.is_empty()) + .map(|s| s.parse().unwrap_or(0)) + .collect::>() + }) + .collect::>>(); + let operators = input + .lines() + .last() + .unwrap() + .split(" ") + .filter(|s| !s.is_empty()); + operators + .enumerate() + .map(|(i, operator)| match operator { + "+" => number_rows.iter().map(|row| row[i]).sum(), + "*" => number_rows.iter().map(|row| row[i]).product(), + _ => 0, + }) + .sum1() +} + +pub fn part_two(input: &str) -> Option { + let operators = input + .lines() + .last() + .unwrap() + .split(" ") + .filter(|s| !s.is_empty()); + let number_rows = input + .lines() + .filter(|line| { + !line.is_empty() && line.chars().find(|c| *c != ' ').unwrap_or(' ').is_numeric() + }) + .map(|line| line.chars().collect()) + .collect::>>(); + + let width = input.lines().map(|line| line.len()).max().unwrap_or(0); + let height = input + .lines() + .filter(|line| { + !line.is_empty() && line.chars().find(|c| *c != ' ').unwrap_or(' ').is_numeric() + }) + .count(); + let mut chunks = vec![]; + let mut curr_chunk = vec![]; + for col in 0..width { + let mut chars = vec![]; + for row in 0..height { + if col >= number_rows[row].len() { + chars.push(' '); + } else { + chars.push(number_rows[row][col]); + } + } + let num_str = chars.iter().join(""); + if num_str.trim().is_empty() { + chunks.push(curr_chunk); + curr_chunk = vec![]; + } else { + curr_chunk.push(num_str.trim().parse().unwrap()); + } + } + chunks.push(curr_chunk); + + operators + .enumerate() + .map(|(i, operator)| match operator { + "+" => chunks[i].iter().sum(), + "*" => chunks[i].iter().product(), + _ => 0, + }) + .sum1() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(4277556)); + } + + #[test] + fn test_part_two() { + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(3263827)); + } +}