day2, pt1
This commit is contained in:
parent
f5c9c54214
commit
f89520a125
4 changed files with 88 additions and 1 deletions
4
Cargo.lock
generated
4
Cargo.lock
generated
|
@ -9,6 +9,10 @@ dependencies = [
|
|||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "day02"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.7.4"
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["day01"]
|
||||
members = ["day01", "day02"]
|
||||
|
||||
[workspace.dependencies]
|
||||
winnow = "0.6"
|
||||
|
|
6
day02/Cargo.toml
Normal file
6
day02/Cargo.toml
Normal file
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "day02"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
77
day02/src/main.rs
Normal file
77
day02/src/main.rs
Normal file
|
@ -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<Vec<i64>> {
|
||||
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);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue