Compare commits

..

No commits in common. "342dd2982ae10c5cdd4f8ffd69972ae47be38940" and "cf586d17155744e4d3b0c19affb8a3e4dbadc977" have entirely different histories.

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::{opt, separated, separated_pair, seq}, combinator::{eof, opt, separated, separated_pair, seq},
}; };
fn main() { fn main() {
@ -16,21 +16,16 @@ 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, false) { if check(eq) {
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
} }
@ -51,7 +46,7 @@ impl Equation {
} }
} }
fn check(equation: &Equation, pt2: bool) -> bool { fn check(equation: &Equation) -> 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;
@ -76,17 +71,10 @@ fn check(equation: &Equation, pt2: bool) -> 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 && cur_idx == (equation.factors.len() - 1) { if cur_val == target {
return true; return true;
} }
processed.insert(current); processed.insert(current);
@ -96,10 +84,6 @@ fn check(equation: &Equation, pt2: bool) -> 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,
@ -112,8 +96,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>, _) = let (equations, _): (Vec<Equation>, _) = seq!(
seq!(separated(1.., parse_equation, newline), opt(newline)) separated(1.., parse_equation, newline),
seq!(opt(newline), opt(eof))
)
.parse(input) .parse(input)
.unwrap(); .unwrap();
equations equations
@ -141,6 +127,6 @@ mod test {
#[test] #[test]
fn p2() { fn p2() {
assert_eq!(11387, pt2(TEST_INPUT)); assert_eq!(0, pt2(TEST_INPUT));
} }
} }