Skip to content
This repository has been archived by the owner on Dec 25, 2024. It is now read-only.

Commit

Permalink
Clean up day 19
Browse files Browse the repository at this point in the history
  • Loading branch information
yamgent committed Dec 19, 2024
1 parent 14a46fe commit a242b7b
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 additions & 15 deletions src/bin/day19/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ use ahash::{HashMap, HashMapExt};

const ACTUAL_INPUT: &str = include_str!("../../../actual_inputs/2024/19/input.txt");

fn p1(input: &str) -> String {
struct Input<'a> {
towels: Vec<&'a str>,
patterns: Vec<&'a str>,
}

fn parse_input(input: &str) -> Input {
let (towels, patterns) = input
.trim()
.split_once("\n\n")
Expand All @@ -11,7 +16,14 @@ fn p1(input: &str) -> String {
let towels = towels.split(",").map(|s| s.trim()).collect::<Vec<_>>();
let patterns = patterns.lines().map(|s| s.trim()).collect::<Vec<_>>();

patterns
Input { towels, patterns }
}

fn p1(input: &str) -> String {
let input = parse_input(input);

input
.patterns
.into_iter()
.filter(|pattern| {
fn check(pattern: &str, towels: &[&str], current_idx: usize) -> bool {
Expand All @@ -30,26 +42,21 @@ fn p1(input: &str) -> String {
}
}

check(pattern, &towels, 0)
check(pattern, &input.towels, 0)
})
.count()
.to_string()
}

fn p2(input: &str) -> String {
let (towels, patterns) = input
.trim()
.split_once("\n\n")
.expect("input has two sections");

let towels = towels.split(",").map(|s| s.trim()).collect::<Vec<_>>();
let patterns = patterns.lines().map(|s| s.trim()).collect::<Vec<_>>();
let mut dp: HashMap<&str, usize> = HashMap::new();
let input = parse_input(input);
let mut dp = HashMap::new();

patterns
input
.patterns
.into_iter()
.map(|pattern| {
fn check<'a>(
fn count<'a>(
dp: &mut HashMap<&'a str, usize>,
pattern: &'a str,
towels: &[&str],
Expand All @@ -68,7 +75,7 @@ fn p2(input: &str) -> String {
if pattern.len() - current_idx >= towel.len()
&& pattern[current_idx..(current_idx + towel.len())] == **towel
{
check(dp, pattern, towels, current_idx + towel.len())
count(dp, pattern, towels, current_idx + towel.len())
} else {
0
}
Expand All @@ -81,7 +88,7 @@ fn p2(input: &str) -> String {
}
}

check(&mut dp, pattern, &towels, 0)
count(&mut dp, pattern, &input.towels, 0)
})
.sum::<usize>()
.to_string()
Expand Down

0 comments on commit a242b7b

Please sign in to comment.