day3 part 1

This commit is contained in:
Joe Ardent 2024-12-21 17:16:29 -08:00
parent 9b4ec1337e
commit 7c962a202b
5 changed files with 92 additions and 22 deletions

7
Cargo.lock generated
View file

@ -13,6 +13,13 @@ dependencies = [
name = "day02"
version = "0.1.0"
[[package]]
name = "day03"
version = "0.1.0"
dependencies = [
"winnow",
]
[[package]]
name = "memchr"
version = "2.7.4"

View file

@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["day01", "day02"]
members = ["day01", "day02", "day03"]
[workspace.dependencies]
winnow = "0.6"

View file

@ -27,6 +27,23 @@ fn pt1(input: &str) -> usize {
safe
}
fn pt2(input: &str) -> usize {
let input = parse(input);
let mut safe = 0;
for line in input.iter() {
for i in 0..(line.len()) {
let left = &line[0..i];
let right = &line[(i + 1)..(line.len())];
let line: Vec<i64> = left.iter().cloned().chain(right.iter().cloned()).collect();
if safe_line(&line) {
safe += 1;
break;
}
}
}
safe
}
fn safe_line(line: &[i64]) -> bool {
let mut dir = None;
let mut last = None;
@ -54,27 +71,6 @@ fn safe_line(line: &[i64]) -> bool {
lsafe
}
fn pt2(input: &str) -> usize {
let input = parse(input);
let mut safe = 0;
for line in input.iter() {
if safe_line(line) {
safe += 1;
} else {
for i in 0..(line.len()) {
let left = &line[0..i];
let right = &line[(i + 1)..(line.len())];
let line: Vec<i64> = left.iter().cloned().chain(right.iter().cloned()).collect();
if safe_line(&line) {
safe += 1;
break;
}
}
}
}
safe
}
fn parse(input: &str) -> Vec<Vec<i64>> {
let mut lines = Vec::new();
for line in input.split("\n").filter(|s| !s.is_empty()) {

7
day03/Cargo.toml Normal file
View file

@ -0,0 +1,7 @@
[package]
name = "day03"
version = "0.1.0"
edition = "2024"
[dependencies]
winnow.workspace = true

60
day03/src/main.rs Normal file
View file

@ -0,0 +1,60 @@
use winnow::{
PResult, Parser,
ascii::dec_int,
combinator::{alt, delimited, preceded, separated_pair},
token::any,
};
fn main() {
let input = std::fs::read_to_string("input").unwrap();
println!("{}", pt1(&input));
}
#[derive(Debug, PartialEq, Eq)]
enum Inst {
Mul(i32, i32),
}
fn pt1(input: &str) -> i32 {
let mut input = input;
let v = parse(&mut input).unwrap();
v.iter().map(|Inst::Mul(a, b)| (a * b)).sum()
}
fn parse_inst(input: &mut &str) -> PResult<Inst> {
let _ = "mul".parse_next(input)?;
let pair: (i32, i32) =
delimited('(', separated_pair(dec_int, ',', dec_int), ')').parse_next(input)?;
Ok(Inst::Mul(pair.0, pair.1))
}
fn parse(input: &mut &str) -> PResult<Vec<Inst>> {
// why can't I just do `repeat(0.., alt((parse_inst, preceded(any,
// parse_inst))))` and call it a day?
let mut v = Vec::new();
loop {
if input.is_empty() {
break;
}
match alt((parse_inst, preceded(any, parse_inst))).parse_next(input) {
Ok(i) => {
v.push(i);
}
Err(_e) => {}
}
}
Ok(v)
}
#[cfg(test)]
mod test {
use super::*;
static INPUT: &str = "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))";
#[test]
fn p1() {
let v = pt1(INPUT);
assert_eq!(v, 161)
}
}