day19 shorter
This commit is contained in:
20
19/main.ml
20
19/main.ml
@@ -13,23 +13,16 @@ let get_input_lists list_of_lines =
|
|||||||
| towels_list :: _ :: tail -> (towels_list, tail)
|
| towels_list :: _ :: tail -> (towels_list, tail)
|
||||||
| _ -> raise (Invalid_argument "Not enough lines")
|
| _ -> raise (Invalid_argument "Not enough lines")
|
||||||
|
|
||||||
let rec try_any_towel cache towels pattern =
|
let rec try_construct cache towels pattern =
|
||||||
towels
|
match Hashtbl.find_opt cache pattern with
|
||||||
|
| Some result -> result
|
||||||
|
| None ->
|
||||||
|
let result = towels
|
||||||
|> List.filter (fun towel ->
|
|> List.filter (fun towel ->
|
||||||
String.starts_with ~prefix:towel pattern)
|
String.starts_with ~prefix:towel pattern)
|
||||||
|> List.map (fun towel ->
|
|> List.map (fun towel ->
|
||||||
try_construct cache towels (String.sub pattern (String.length towel) (String.length pattern - String.length towel)))
|
try_construct cache towels (String.sub pattern (String.length towel) (String.length pattern - String.length towel)))
|
||||||
|> List.fold_left Int.add 0
|
|> List.fold_left Int.add 0 in
|
||||||
|
|
||||||
and try_construct cache towels pattern =
|
|
||||||
if String.length pattern = 0 then
|
|
||||||
1
|
|
||||||
else
|
|
||||||
match Hashtbl.find_opt cache pattern with
|
|
||||||
| Some result ->
|
|
||||||
result
|
|
||||||
| None ->
|
|
||||||
let result = try_any_towel cache towels pattern in
|
|
||||||
Hashtbl.add cache pattern result;
|
Hashtbl.add cache pattern result;
|
||||||
result
|
result
|
||||||
|
|
||||||
@@ -38,6 +31,7 @@ let () =
|
|||||||
let towels_str, patterns_list = list_of_lines f |> get_input_lists in
|
let towels_str, patterns_list = list_of_lines f |> get_input_lists in
|
||||||
let towels_list = towels_str |> String.split_on_char ',' |> List.map (fun x -> x |> String.trim) in
|
let towels_list = towels_str |> String.split_on_char ',' |> List.map (fun x -> x |> String.trim) in
|
||||||
let cache = Hashtbl.create 1024 in
|
let cache = Hashtbl.create 1024 in
|
||||||
|
Hashtbl.add cache "" 1;
|
||||||
let possibilities_list = patterns_list |> List.map (try_construct cache towels_list) in
|
let possibilities_list = patterns_list |> List.map (try_construct cache towels_list) in
|
||||||
let result = possibilities_list |> List.filter (fun x-> x > 0) |> List.length in
|
let result = possibilities_list |> List.filter (fun x-> x > 0) |> List.length in
|
||||||
let result2 = List.fold_left Int.add 0 possibilities_list in
|
let result2 = List.fold_left Int.add 0 possibilities_list in
|
||||||
|
Reference in New Issue
Block a user