From 2f28563f06f4d2b2f501e08d86ba3d142c7bc050 Mon Sep 17 00:00:00 2001 From: brian Date: Tue, 3 Dec 2024 09:53:39 -0800 Subject: solution for day 3 --- lib/day3.ml | 39 +++++++++++++++++++++++++++++++++------ lib/dune | 2 +- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/lib/day3.ml b/lib/day3.ml index 5f433e2..0b13155 100644 --- a/lib/day3.ml +++ b/lib/day3.ml @@ -1,24 +1,51 @@ open! Imports +open! Core module M = struct (* Type to parse the input into *) - type t = unit + type t = Re.Group.t list (* Parse the input to type t, invoked for both parts *) - let parse _inputs = () + let parse inputs = + let regex = Re.compile @@ Re.Pcre.re "mul\((\d{1,3}),(\d{1,3})\)|do\(\)|don\'t\(\)" in + Re.all regex inputs (* Run part 1 with parsed inputs *) - let part1 _ = () + let part1 inputs = + inputs + |> List.map ~f:(fun group -> + match Re.Group.get_opt group 1 with + | Some _ -> (int_of_string @@ Re.Group.get group 1, int_of_string @@ Re.Group.get group 2) + | None -> 0, 0) + |> List.fold ~init:0 ~f:(fun acc (a, b) -> acc + (a * b)) + |> print_endline_int (* Run part 2 with parsed inputs *) - let part2 _ = () + let part2 inputs = + let rec helper acc instructions enabled = + match instructions with + | [] -> acc + | curr_inst::tail -> + match Re.Group.get curr_inst 0 with + | "do()" -> helper acc tail true + | "don't()" -> helper acc tail false + | _ -> if enabled then + let product = (int_of_string @@ Re.Group.get curr_inst 1) * (int_of_string @@ Re.Group.get curr_inst 2) in + helper (acc + product) tail enabled + else helper acc tail enabled in + helper 0 inputs true + |> print_endline_int + end include M include Day.Make (M) (* Example input *) -let example = "" +let example = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))" (* Expect test for example input *) -let%expect_test _ = run example ; [%expect {| |}] +let%expect_test _ = run example ; [%expect {| + 161 + 48 + |}] diff --git a/lib/dune b/lib/dune index 2acb50c..e82cbd0 100644 --- a/lib/dune +++ b/lib/dune @@ -1,6 +1,6 @@ (library (name aoc) (inline_tests) - (libraries unix core str) + (libraries unix core str re) (preprocess (pps ppx_expect))) -- cgit