summaryrefslogtreecommitdiff
path: root/2024/OCaml/lib/day_01/part_02.ml
diff options
context:
space:
mode:
authorDJ O'Leary <dijitol@proton.me>2025-03-03 00:56:33 +0100
committerDJ O'Leary <dijitol@proton.me>2025-03-03 00:56:33 +0100
commite24effa8fd3574e9d396be0e1a47f101c27c0a60 (patch)
tree793896d20384facd10d925e09f8f0dd89c930cce /2024/OCaml/lib/day_01/part_02.ml
perf: Merge Advent of Code year specific repos
Diffstat (limited to '2024/OCaml/lib/day_01/part_02.ml')
-rw-r--r--2024/OCaml/lib/day_01/part_02.ml43
1 files changed, 43 insertions, 0 deletions
diff --git a/2024/OCaml/lib/day_01/part_02.ml b/2024/OCaml/lib/day_01/part_02.ml
new file mode 100644
index 0000000..532b344
--- /dev/null
+++ b/2024/OCaml/lib/day_01/part_02.ml
@@ -0,0 +1,43 @@
+(* Day 1: Part 2 *)
+
+let rec count_occurrances_help element acc lst =
+ match lst with
+ | [] -> acc
+ | h :: t ->
+ if h = element then count_occurrances_help element (acc + 1) t
+ else count_occurrances_help element acc t
+
+let count_occurrances element lst = count_occurrances_help element 0 lst
+
+let solve left right =
+ List.map (fun x -> x * count_occurrances x right) left |> List.fold_left ( + ) 0
+
+let left line =
+ let pos = 0 in
+ let len = String.index line ' ' in
+ String.sub line pos len
+
+let right line =
+ let pos = String.rindex line ' ' + 1 in
+ let len = String.length line - pos in
+ String.sub line pos len
+
+let line_to_tuple line = (left line, right line)
+
+let lines_to_lists lines =
+ let tuples = List.map line_to_tuple lines in
+ let left =
+ List.map
+ (fun t ->
+ let l, _ = t in
+ int_of_string l)
+ tuples
+ in
+ let right =
+ List.map
+ (fun t ->
+ let _, r = t in
+ int_of_string r)
+ tuples
+ in
+ (left, right)