diff --git a/02/Cargo.lock b/02/Cargo.lock new file mode 100644 index 0000000..ae33267 --- /dev/null +++ b/02/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aoc2024-02" +version = "0.1.0" diff --git a/02/Cargo.toml b/02/Cargo.toml new file mode 100644 index 0000000..a39e8d3 --- /dev/null +++ b/02/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "aoc2024-02" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/02/src/main.rs b/02/src/main.rs new file mode 100644 index 0000000..787d540 --- /dev/null +++ b/02/src/main.rs @@ -0,0 +1,65 @@ +fn is_safe(items: &Vec) -> bool { + let deltas: Vec<_> = items + .iter() + .scan(None, |p, s| match p.clone() { + None => { + *p = Some(*s); + Some(None) + } + Some(v) => { + *p = Some(*s); + Some(Some(*s - v)) + } + }) + .flatten() + .collect(); + if deltas.iter().all(|x| *x >= 1 && *x <= 3) || deltas.iter().all(|x| *x >= -3 && *x <= -1) { + true + } else { + false + } +} + +fn main() { + let raw = std::fs::read_to_string("input.txt").expect("Couldn't read input"); + let first: i32 = raw + .split("\n") + .filter(|line| !line.is_empty()) + .map(|line| { + let items = line + .split(" ") + .map(|x| x.parse()) + .collect::, _>>() + .unwrap(); + if is_safe(&items) { + 1 + } else { + 0 + } + }) + .sum(); + println!("{}", first); + let second: i32 = raw + .split("\n") + .filter(|line| !line.is_empty()) + .map(|line| { + let items = line + .split(" ") + .map(|x| x.parse()) + .collect::, _>>() + .unwrap(); + if is_safe(&items) { + 1 + } else if (0..items.len()).any(|i| { + let mut items = items.clone(); + items.remove(i); + is_safe(&items) + }) { + 1 + } else { + 0 + } + }) + .sum(); + println!("{}", second); +}