day 2, rust

master
Codinget 2 months ago
parent df1ea7405a
commit a163e6dea2
  1. 7
      02/Cargo.lock
  2. 6
      02/Cargo.toml
  3. 65
      02/src/main.rs

7
02/Cargo.lock generated

@ -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"

@ -0,0 +1,6 @@
[package]
name = "aoc2024-02"
version = "0.1.0"
edition = "2021"
[dependencies]

@ -0,0 +1,65 @@
fn is_safe(items: &Vec<i32>) -> 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::<Result<Vec<i32>, _>>()
.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::<Result<Vec<i32>, _>>()
.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);
}
Loading…
Cancel
Save