Advent of Code solutions

Day 2

bwc9876.dev 3bd7bac8 7093b440

verified
+52 -6
+1 -1
justfile
··· 3 3 cargo run --release -- solve * 4 4 5 5 year := `date +%Y` 6 - day := `date +%d` 6 + day := `nu -c 'date now | format date "%_d" | str trim'` 7 7 8 8 p P in="": 9 9 cargo run --release -- solve {{year}}:{{day}}:{{P}} {{in}}
+39 -5
years/2024/src/day_2.rs
··· 3 3 4 4 pub struct Day2; 5 5 6 + fn line_valid(line: &[u64]) -> bool { 7 + let mut increasing: Option<bool> = None; 8 + line.windows(2).all(|w| { 9 + let (x, y) = (w[0], w[1]); 10 + if x == y || x.abs_diff(y) > 3 { 11 + false 12 + } else if let Some(increasing) = increasing { 13 + !((increasing && y <= x) || (!increasing && x <= y)) 14 + } else { 15 + increasing = Some(x < y); 16 + true 17 + } 18 + }) 19 + } 20 + 6 21 impl Day for Day2 { 7 22 8 - day_stuff!(2, "", ""); 23 + day_stuff!(2, "2", "4", Vec<Vec<u64>>); 9 24 10 - fn part_1(_input: Self::Input) -> Option<String> { 11 - None 25 + fn part_1(input: Self::Input) -> Option<String> { 26 + Some(input.into_iter().filter(|v| line_valid(&v)).count().to_string()) 12 27 } 13 28 14 - fn part_2(_input: Self::Input) -> Option<String> { 15 - None 29 + fn part_2(input: Self::Input) -> Option<String> { 30 + Some(input.into_iter().filter(|line| { 31 + let valid = line_valid(&line); 32 + if valid { 33 + true 34 + } else { 35 + (0..line.len()).any(|ie| { 36 + let v = line.iter() 37 + .enumerate() 38 + .filter(|(i, _)| *i != ie) 39 + .map(|(_, e)| *e) 40 + .collect::<Vec<_>>(); 41 + 42 + line_valid(&v) 43 + }) 44 + } 45 + }).count().to_string()) 46 + } 47 + 48 + fn parse_input(input: &str) -> Self::Input { 49 + input.split('\n').map(|l| l.split_ascii_whitespace().map(|x| x.parse::<u64>().unwrap()).collect()).collect() 16 50 } 17 51 }
+6
years/2024/src/examples/day_2/1.txt
··· 1 + 7 6 4 2 1 2 + 1 2 7 8 9 3 + 9 7 6 2 1 4 + 1 3 2 4 5 5 + 8 6 4 4 1 6 + 1 3 6 7 9
+6
years/2024/src/examples/day_2/2.txt
··· 1 + 7 6 4 2 1 2 + 1 2 7 8 9 3 + 9 7 6 2 1 4 + 1 3 2 4 5 5 + 8 6 4 4 1 6 + 1 3 6 7 9