1
0

Compare commits

..

3 Commits

Author SHA1 Message Date
48f9790c5e clippy 2024-12-02 19:13:13 +01:00
df7b7ae445 day 2 part 2 2024-12-02 19:11:47 +01:00
1bcd38be17 day 2 part 1 2024-12-02 19:01:49 +01:00
3 changed files with 62 additions and 10 deletions

View File

@@ -15,10 +15,7 @@ fn part1(input: &str) -> Int {
l.sort(); l.sort();
r.sort(); r.sort();
l.into_iter() l.into_iter().zip(r).map(|(l, r)| (l - r).abs()).sum()
.zip(r.into_iter())
.map(|(l, r)| (l - r).abs())
.sum()
} }
fn part2(input: &str) -> Int { fn part2(input: &str) -> Int {

View File

@@ -1,17 +1,71 @@
use std::fs::read_to_string; use std::fs::read_to_string;
use itertools::Itertools;
pub fn day_main() { pub fn day_main() {
let input = read_to_string("input/day01.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));
} }
type Int = i32; fn part1(input: &str) -> usize {
input
.lines()
.map(|line| {
line.split_whitespace()
.map(|s| s.parse::<i32>().unwrap())
.collect_vec()
})
.filter(|report: &Vec<i32>| is_safe(report))
.count()
}
fn part1(input: &str) -> Int { fn part2(input: &str) -> usize {
0 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()
}
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
// } // }
#[cfg(test)]
mod test {
#[test]
fn part1() {
let input = r"7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9";
assert_eq!(2, super::part1(input));
}
}

View File

@@ -1,11 +1,12 @@
use std::env::args; use std::env::args;
use advent_of_rust_2024::day01; use advent_of_rust_2024::{day01, day02};
fn main() { fn main() {
let day: Option<u8> = args().nth(1).and_then(|a| a.parse().ok()); let day: Option<u8> = args().nth(1).and_then(|a| a.parse().ok());
match day { match day {
Some(1) => day01::day_main(), Some(1) => day01::day_main(),
Some(2) => day02::day_main(),
_ => println!("hi"), _ => println!("hi"),
} }
} }