Use variants for day 3.

This commit is contained in:
2024-12-03 15:38:53 +00:00
parent 2ee7f6a3d3
commit 1f99f23c92

View File

@@ -1,6 +1,4 @@
(** [matched_group_opt n s] returns [Some (Str.matched_group n s)] if the [n]th type cmd = Do | Donot | Mul of int * int
group matched, or [None] if the group did not match. *)
let matched_group_opt n s = try Some (Str.matched_group n s) with _ -> None
(** [find_nums s] returns the list of instructions given in [s]. *) (** [find_nums s] returns the list of instructions given in [s]. *)
let instrs_of_string s = let instrs_of_string s =
@@ -11,12 +9,16 @@ let instrs_of_string s =
let rec impl acc pos = let rec impl acc pos =
try try
let _ = Str.search_forward r s pos in let _ = Str.search_forward r s pos in
let p0 = Str.matched_group 0 s in let action =
let p1 = matched_group_opt 1 s in match Str.matched_group 0 s with
let p2 = matched_group_opt 2 s in | "do()" -> Do
impl | "don't()" -> Donot
((p0, Option.map int_of_string p1, Option.map int_of_string p2) :: acc) | _ ->
(Str.match_end ()) Mul
( int_of_string (Str.matched_group 1 s),
int_of_string (Str.matched_group 2 s) )
in
impl (action :: acc) (Str.match_end ())
with Not_found -> acc with Not_found -> acc
in in
List.rev (impl [] 0) List.rev (impl [] 0)
@@ -24,20 +26,18 @@ let instrs_of_string s =
let instrs_of_file fname = let instrs_of_file fname =
Aoc.strings_of_file fname |> List.map instrs_of_string |> List.concat Aoc.strings_of_file fname |> List.map instrs_of_string |> List.concat
(** [mac_opt acc a b] returns [acc + a' * b'] if [a = Some a'] and (** [mac acc a b] returns [acc + a * b]. *)
[b = Some b']. If either [a] or [b] are [None] then the result is [acc]. *) let mac acc = function Mul (a, b) -> acc + (a * b) | _ -> acc
let mac_opt acc a b =
acc + (Option.value a ~default:0 * Option.value b ~default:0)
let day2403a = List.fold_left (fun acc (_, a, b) -> mac_opt acc a b) 0 let day2403a = List.fold_left mac 0
let day2403b lst = let day2403b lst =
let rec impl acc enabled = function let rec impl acc enabled = function
| [] -> acc | [] -> acc
| ("do()", _, _) :: t -> impl acc true t | Do :: t -> impl acc true t
| ("don't()", _, _) :: t -> impl acc false t | Donot :: t -> impl acc false t
| (_, a, b) :: t -> | Mul (a, b) :: t ->
if enabled then impl (mac_opt acc a b) true t else impl acc false t if enabled then impl (acc + (a * b)) true t else impl acc false t
in in
impl 0 true lst impl 0 true lst