diff options
| author | DJ O'Leary <dijitol@proton.me> | 2025-11-29 20:23:02 +0100 |
|---|---|---|
| committer | DJ O'Leary <dijitol@proton.me> | 2025-11-29 20:23:02 +0100 |
| commit | 4c3a50166bf0f78ce89459c352cc1c6536a8b96d (patch) | |
| tree | 02e4b66a1435680ef1e92bf82576747b27f16447 /2024/ocaml/lib/day_01 | |
| parent | be2f8528b3829f8263507da301812d852297c168 (diff) | |
chore: make language folders snake_case
Diffstat (limited to '2024/ocaml/lib/day_01')
| -rw-r--r-- | 2024/ocaml/lib/day_01/part_01.ml | 40 | ||||
| -rw-r--r-- | 2024/ocaml/lib/day_01/part_02.ml | 44 |
2 files changed, 84 insertions, 0 deletions
diff --git a/2024/ocaml/lib/day_01/part_01.ml b/2024/ocaml/lib/day_01/part_01.ml new file mode 100644 index 0000000..100b12a --- /dev/null +++ b/2024/ocaml/lib/day_01/part_01.ml @@ -0,0 +1,40 @@ +(* Day 1: Part 1 *) + +let calculate_distance x y = Stdlib.abs (x - y) + +(** Require: left and right to be the same length *) +let solve left right = + let sorted_left = List.sort Stdlib.compare left in + let sorted_right = List.sort Stdlib.compare right in + let distances = List.map2 calculate_distance sorted_left sorted_right in + List.fold_left ( + ) 0 distances + +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) 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..25c8b7d --- /dev/null +++ b/2024/ocaml/lib/day_01/part_02.ml @@ -0,0 +1,44 @@ +(* 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) |
