use aoc; use std::io::{BufReader, Read}; use aoc::Day; struct Day1 {} impl Day1 { fn part_n(&self, input: BufReader>) -> (Vec, Vec) { let mut a: Vec = vec![]; let mut b: Vec = vec![]; for line in self.read_lines(input) { let mut s = line.split(' '); loop { let ia = s.next().unwrap(); let num = match ia.parse::() { Ok(num) => num, Err(_) => continue, }; a.push(num); break; } loop { let ib = s.next_back().unwrap(); let num = match ib.parse::() { Ok(num) => num, Err(_) => continue, }; b.push(num); break; } } (a, b) } } impl Day for Day1 { fn example_input(&self) -> &'static str { r#" 3 4 4 3 2 5 1 3 3 9 3 3 "#.trim() } fn example_result_part_1(&self) -> &'static str { "11" } fn example_result_part_2(&self) -> &'static str { "31" } fn part_1(&self, input: BufReader>) -> String { let (mut a, mut b) = self.part_n(input); a.sort(); b.sort(); let mut distances: Vec = vec![]; for (ia, ib) in a.iter().zip(b) { if *ia > ib { distances.push(ia - ib); } else { distances.push(ib - ia); } } format!("{}", (distances.iter().sum::())) } fn part_2(&self, input: BufReader>) -> String { let (a, b) = self.part_n(input); let mut scores: Vec = vec![]; for item in a { let count = b.iter().filter(|&&i| i == item).count(); scores.push(item * count as u32); } format!("{}", (scores.iter().sum::())) } } fn main() { aoc::main(&Day1 {}); } #[cfg(test)] mod tests { use super::*; #[test] fn test_day1() { aoc::test_day(&Day1 {}); } }