Code for the Advent of Code event
aoc advent-of-code
at rust 87 lines 1.8 kB view raw
1use aoc_macros::aoc; 2 3#[aoc(2024, 2, 1)] 4pub fn part1(input: &str) -> String { 5 // Example solution for 2024 Day 2 Part 1 6 let reports: Vec<Vec<i32>> = input 7 .trim() 8 .lines() 9 .map(|line| { 10 line.split_whitespace() 11 .map(|n| n.parse().unwrap()) 12 .collect() 13 }) 14 .collect(); 15 16 let safe_count = reports 17 .iter() 18 .filter(|report| is_safe_report(report)) 19 .count(); 20 21 safe_count.to_string() 22} 23 24#[aoc(2024, 2, 2)] 25pub fn part2(input: &str) -> String { 26 // Example solution for 2024 Day 2 Part 2 27 let reports: Vec<Vec<i32>> = input 28 .trim() 29 .lines() 30 .map(|line| { 31 line.split_whitespace() 32 .map(|n| n.parse().unwrap()) 33 .collect() 34 }) 35 .collect(); 36 37 let safe_count = reports 38 .iter() 39 .filter(|report| is_safe_with_dampener(report)) 40 .count(); 41 42 safe_count.to_string() 43} 44 45fn is_safe_report(report: &[i32]) -> bool { 46 if report.len() < 2 { 47 return true; 48 } 49 50 let increasing = report[1] > report[0]; 51 52 for window in report.windows(2) { 53 let diff = window[1] - window[0]; 54 let abs_diff = diff.abs(); 55 56 if !(1..=3).contains(&abs_diff) { 57 return false; 58 } 59 60 if increasing && diff <= 0 { 61 return false; 62 } 63 64 if !increasing && diff >= 0 { 65 return false; 66 } 67 } 68 69 true 70} 71 72fn is_safe_with_dampener(report: &[i32]) -> bool { 73 if is_safe_report(report) { 74 return true; 75 } 76 77 // Try removing each level 78 for i in 0..report.len() { 79 let mut modified = report.to_vec(); 80 modified.remove(i); 81 if is_safe_report(&modified) { 82 return true; 83 } 84 } 85 86 false 87}