From f89520a1255b928b29734f7786325f749a1c1fbc Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Sun, 15 Dec 2024 16:25:56 -0800 Subject: [PATCH] day2, pt1 --- Cargo.lock | 4 +++ Cargo.toml | 2 +- day02/Cargo.toml | 6 ++++ day02/src/main.rs | 77 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 day02/Cargo.toml create mode 100644 day02/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index c91b0cb..912c1b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9,6 +9,10 @@ dependencies = [ "winnow", ] +[[package]] +name = "day02" +version = "0.1.0" + [[package]] name = "memchr" version = "2.7.4" diff --git a/Cargo.toml b/Cargo.toml index 6cbd0ee..4668a35 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["day01"] +members = ["day01", "day02"] [workspace.dependencies] winnow = "0.6" diff --git a/day02/Cargo.toml b/day02/Cargo.toml new file mode 100644 index 0000000..3304419 --- /dev/null +++ b/day02/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day02" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/day02/src/main.rs b/day02/src/main.rs new file mode 100644 index 0000000..1c10151 --- /dev/null +++ b/day02/src/main.rs @@ -0,0 +1,77 @@ +fn main() { + let input = std::fs::read_to_string("input").unwrap(); + println!("{}", pt1(&input)); +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +enum Sign { + Pos, + Neg, +} + +impl Sign { + fn new(s: i64) -> Self { + if s.signum() < 0 { Sign::Neg } else { Sign::Pos } + } +} + +fn pt1(input: &str) -> usize { + let input = parse(input); + let mut safe = 0; + for line in input.iter() { + let mut dir = None; + let mut last = None; + let mut lsafe = true; + for v in line.iter() { + if let Some(l) = last { + last = Some(v); + let d = v - l; + let s = Sign::new(d); + if let Some(p) = dir { + if p != s { + lsafe = false; + break; + } + } + dir = Some(s); + if d.abs() > 3 || d.abs() < 1 { + lsafe = false; + break; + } + } else { + last = Some(v); + } + } + if lsafe { + safe += 1; + } + } + + safe +} + +fn parse(input: &str) -> Vec> { + let mut lines = Vec::new(); + for line in input.split("\n").filter(|s| !s.is_empty()) { + let l = line.split(' ').map(|n| n.parse().unwrap()).collect(); + lines.push(l); + } + lines +} + +mod test { + use super::*; + + static INPUT: &str = "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"; + + #[test] + fn tp1() { + let safe = pt1(INPUT); + assert_eq!(2, safe); + } +}