2024 day 19 part 2.

This commit is contained in:
2024-12-19 11:10:16 +00:00
parent 33d7b34002
commit 4c9ae83184

View File

@@ -31,14 +31,35 @@ let rec memoize_has_pattern pattern towels =
x x
let has_match towels pattern = memoize_has_pattern pattern towels let has_match towels pattern = memoize_has_pattern pattern towels
let memo2 = Hashtbl.create 1000
let rec memoize_count_matches pattern towels =
let pattern_len = String.length pattern in
let rec has_pattern = function
| [] -> 0
| h :: t ->
let towel_len = String.length h in
if String.starts_with ~prefix:h pattern then
memoize_count_matches
(String.sub pattern towel_len (pattern_len - towel_len))
towels
+ has_pattern t
else has_pattern t
in
match Hashtbl.find_opt memo2 pattern with
| Some x -> x
| None ->
let x = if pattern_len = 0 then 1 else has_pattern towels in
Hashtbl.add memo2 pattern x;
x
let count_matches towels pattern = memoize_count_matches pattern towels
let part1 (towels, patterns) = let part1 (towels, patterns) =
List.filter List.filter (has_match towels) patterns |> List.length
(fun p ->
let x = has_match towels p in
flush stdout;
x)
patterns
|> List.length
let _ = Aoc.main towels_of_file [ (string_of_int, part1) ] let part2 (towels, patterns) =
List.map (count_matches towels) patterns |> List.fold_left ( + ) 0
let _ =
Aoc.main towels_of_file [ (string_of_int, part1); (string_of_int, part2) ]