aboutsummaryrefslogtreecommitdiff
path: root/2024/day_01.ml
diff options
context:
space:
mode:
authorTrey Bastian <2991824+TreyBastian@users.noreply.github.com>2024-12-04 13:43:12 +0000
committerTrey Bastian <2991824+TreyBastian@users.noreply.github.com>2024-12-04 13:43:12 +0000
commit172cecd0ad1aaea451ee5da3e134cf513ecc8521 (patch)
tree04fe883a525ca4f1425f719dfa76fca6efd03e34 /2024/day_01.ml
parentb9210dcc5c52f2069d92e7a3e66f92be96075f94 (diff)
ocaml day 1 done
Diffstat (limited to '2024/day_01.ml')
-rw-r--r--2024/day_01.ml32
1 files changed, 32 insertions, 0 deletions
diff --git a/2024/day_01.ml b/2024/day_01.ml
new file mode 100644
index 0000000..42ee50d
--- /dev/null
+++ b/2024/day_01.ml
@@ -0,0 +1,32 @@
+let filename = "./day_01_input.txt"
+
+let () =
+ let ic = open_in filename in
+
+ let try_read () = try Some (input_line ic) with End_of_file -> None in
+
+ let rec read_lines left right =
+ match try_read () with
+ | Some line -> (
+ let ints =
+ Str.split_delim (Str.regexp " ") line |> List.map int_of_string
+ in
+ match ints with
+ | [ a; b ] -> read_lines (a :: left) (b :: right)
+ | _ -> failwith "invalid")
+ | None ->
+ close_in ic;
+ (List.sort compare left, List.sort compare right)
+ in
+ let left, right = read_lines [] [] in
+ let sum =
+ List.map2 ( - ) left right |> List.map abs |> List.fold_left ( + ) 0
+ in
+ Printf.sprintf "Sum %d" sum |> print_endline;
+ let sim =
+ List.map
+ (fun x -> x * (List.filter (fun y -> x == y) right |> List.length))
+ left
+ |> List.fold_left ( + ) 0
+ in
+ Printf.sprintf "Sim %d" sim |> print_endline