1
0

day 2 part 2

This commit is contained in:
2024-12-02 19:11:47 +01:00
parent 1bcd38be17
commit df7b7ae445

View File

@@ -1,11 +1,11 @@
use std::fs::read_to_string; use std::{default, fs::read_to_string};
use itertools::Itertools; use itertools::Itertools;
pub fn day_main() { pub fn day_main() {
let input = read_to_string("input/day02.txt").unwrap(); let input = read_to_string("input/day02.txt").unwrap();
println!("part1: {}", part1(&input)); println!("part1: {}", part1(&input));
// println!("part2: {}", part2(&input)); println!("part2: {}", part2(&input));
} }
fn part1(input: &str) -> usize { fn part1(input: &str) -> usize {
@@ -16,21 +16,43 @@ fn part1(input: &str) -> usize {
.map(|s| s.parse::<i32>().unwrap()) .map(|s| s.parse::<i32>().unwrap())
.collect_vec() .collect_vec()
}) })
.filter(|report: &Vec<i32>| { .filter(|report: &Vec<i32>| is_safe(report))
let pairs = report .count()
.windows(2) }
.map(|window| window[1] - window[0])
.collect_vec();
let steepest_slope = pairs.iter().map(|x| x.abs()).max().unwrap();
let lowest_slope = pairs.iter().map(|x| x.abs()).min().unwrap();
let same_sign = pairs.iter().map(|x| x.signum()).unique().count() == 1;
println!("{:?} - {steepest_slope}/{same_sign}", report);
steepest_slope <= 3 && lowest_slope >= 1 && same_sign fn part2(input: &str) -> usize {
input
.lines()
.map(|line| {
line.split_whitespace()
.map(|s| s.parse::<i32>().unwrap())
.collect_vec()
})
.filter(|report: &Vec<i32>| {
(0..report.len()).any(|del| {
let without = report
.iter()
.enumerate()
.filter_map(|(i, e)| if del != i { Some(*e) } else { None })
.collect_vec();
is_safe(&without)
})
}) })
.count() .count()
} }
fn is_safe(report: &[i32]) -> bool {
let pairs = report
.windows(2)
.map(|window| window[1] - window[0])
.collect_vec();
let steepest_slope = pairs.iter().map(|x| x.abs()).max().unwrap();
let lowest_slope = pairs.iter().map(|x| x.abs()).min().unwrap();
let same_sign = pairs.iter().map(|x| x.signum()).unique().count() == 1;
steepest_slope <= 3 && lowest_slope >= 1 && same_sign
}
// fn part2(input: &str) -> Int { // fn part2(input: &str) -> Int {
// 0 // 0
// } // }