Compare commits

...

2 commits

Author SHA1 Message Date
Joe Ardent
342dd2982a day7, part2 2024-12-28 13:11:42 -08:00
Joe Ardent
b1110f2b6c d7p2: passes test, fails run 2024-12-28 11:55:59 -08:00

View file

@ -3,7 +3,7 @@ use std::collections::HashSet;
use winnow::{ use winnow::{
PResult, Parser, PResult, Parser,
ascii::{dec_uint, newline, space1}, ascii::{dec_uint, newline, space1},
combinator::{eof, opt, separated, separated_pair, seq}, combinator::{opt, separated, separated_pair, seq},
}; };
fn main() { fn main() {
@ -16,16 +16,21 @@ fn pt1(input: &str) -> u64 {
let mut total = 0; let mut total = 0;
let eqs = parse(input); let eqs = parse(input);
for eq in &eqs { for eq in &eqs {
if check(eq) { if check(eq, false) {
total += eq.total; total += eq.total;
} }
} }
total total
} }
fn pt2(_input: &str) -> u64 { fn pt2(input: &str) -> u64 {
let mut total = 0; let mut total = 0;
let eqs = parse(input);
for eq in &eqs {
if check(eq, true) {
total += eq.total;
}
}
total total
} }
@ -46,7 +51,7 @@ impl Equation {
} }
} }
fn check(equation: &Equation) -> bool { fn check(equation: &Equation, pt2: bool) -> bool {
let mut processed = HashSet::new(); let mut processed = HashSet::new();
let mut q = Vec::new(); let mut q = Vec::new();
let target = equation.total; let target = equation.total;
@ -71,10 +76,17 @@ fn check(equation: &Equation) -> bool {
process_top = false; process_top = false;
q.push(plus); q.push(plus);
} }
if pt2 {
let concat = (next_idx, cat(cur_val, next_val));
if concat.1 <= target && !processed.contains(&concat) {
process_top = false;
q.push(concat);
}
}
} }
if process_top { if process_top {
let _ = q.pop(); let _ = q.pop();
if cur_val == target { if cur_val == target && cur_idx == (equation.factors.len() - 1) {
return true; return true;
} }
processed.insert(current); processed.insert(current);
@ -84,6 +96,10 @@ fn check(equation: &Equation) -> bool {
false false
} }
fn cat(a: u64, b: u64) -> u64 {
format!("{a}{b}").parse().unwrap()
}
fn parse_equation(input: &mut &str) -> PResult<Equation> { fn parse_equation(input: &mut &str) -> PResult<Equation> {
let (total, factors) = separated_pair( let (total, factors) = separated_pair(
dec_uint, dec_uint,
@ -96,12 +112,10 @@ fn parse_equation(input: &mut &str) -> PResult<Equation> {
} }
fn parse(input: &str) -> Vec<Equation> { fn parse(input: &str) -> Vec<Equation> {
let (equations, _): (Vec<Equation>, _) = seq!( let (equations, _): (Vec<Equation>, _) =
separated(1.., parse_equation, newline), seq!(separated(1.., parse_equation, newline), opt(newline))
seq!(opt(newline), opt(eof)) .parse(input)
) .unwrap();
.parse(input)
.unwrap();
equations equations
} }
@ -127,6 +141,6 @@ mod test {
#[test] #[test]
fn p2() { fn p2() {
assert_eq!(0, pt2(TEST_INPUT)); assert_eq!(11387, pt2(TEST_INPUT));
} }
} }