From 33d7b340028d8ef813623e23d082083288d0c793 Mon Sep 17 00:00:00 2001 From: Matthew Gretton-Dann Date: Thu, 19 Dec 2024 11:06:02 +0000 Subject: [PATCH] 2024 day 19 part 1 --- bin/day2419.ml | 44 ++++++++++++++++++++++++++++++++++++++++++++ bin/dune | 6 ++++-- 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 bin/day2419.ml diff --git a/bin/day2419.ml b/bin/day2419.ml new file mode 100644 index 0000000..c0ec9ab --- /dev/null +++ b/bin/day2419.ml @@ -0,0 +1,44 @@ +(** [towels_of_strings lst] returns a pair containing a list of available towels + and a list of patterns wanted. *) +let towels_of_strings = function + | h :: "" :: t -> + let re = Str.regexp "[, ]+" in + let h = Str.split re h in + (h, t) + | _ -> failwith "towels_of_strings" + +let towels_of_file fname = Aoc.strings_of_file fname |> towels_of_strings +let memo = Hashtbl.create 1000 + +let rec memoize_has_pattern pattern towels = + let pattern_len = String.length pattern in + let rec has_pattern = function + | [] -> false + | h :: t -> + let towel_len = String.length h in + if String.starts_with ~prefix:h pattern then + memoize_has_pattern + (String.sub pattern towel_len (pattern_len - towel_len)) + towels + || has_pattern t + else has_pattern t + in + match Hashtbl.find_opt memo pattern with + | Some x -> x + | None -> + let x = if pattern_len = 0 then true else has_pattern towels in + Hashtbl.add memo pattern x; + x + +let has_match towels pattern = memoize_has_pattern pattern towels + +let part1 (towels, patterns) = + List.filter + (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) ] diff --git a/bin/dune b/bin/dune index 625b669..c24ba0f 100644 --- a/bin/dune +++ b/bin/dune @@ -17,7 +17,8 @@ day2415 day2416 day2417 - day2418) + day2418 + day2419) (names day2401 day2402 @@ -36,5 +37,6 @@ day2415 day2416 day2417 - day2418) + day2418 + day2419) (libraries str aoc))