summaryrefslogtreecommitdiff
path: root/2023/ocaml/day4/bin
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2024-02-26 23:16:00 +0100
committerSanto Cariotti <santo@dcariotti.me>2024-02-26 23:17:18 +0100
commit52c33969d7b358cdac40f02a8562e37f82a96135 (patch)
tree0cf9edf687d8f3be524f9b563255204af7f178a7 /2023/ocaml/day4/bin
parent8ff53967fac0ba5c8cee1a248a38e8e0ad1b72ee (diff)
Add day4
Diffstat (limited to '2023/ocaml/day4/bin')
-rw-r--r--2023/ocaml/day4/bin/dune4
-rw-r--r--2023/ocaml/day4/bin/main.ml45
2 files changed, 49 insertions, 0 deletions
diff --git a/2023/ocaml/day4/bin/dune b/2023/ocaml/day4/bin/dune
new file mode 100644
index 0000000..add70da
--- /dev/null
+++ b/2023/ocaml/day4/bin/dune
@@ -0,0 +1,4 @@
+(executable
+ (public_name day4)
+ (name main)
+ (libraries day4))
diff --git a/2023/ocaml/day4/bin/main.ml b/2023/ocaml/day4/bin/main.ml
new file mode 100644
index 0000000..9d1a6ad
--- /dev/null
+++ b/2023/ocaml/day4/bin/main.ml
@@ -0,0 +1,45 @@
+let input_file = "input.txt"
+
+let read_file f =
+ let ic = open_in f in
+ try
+ let lines = really_input_string ic (in_channel_length ic) |> String.trim in
+ close_in ic;
+ lines
+ with e ->
+ close_in_noerr ic;
+ raise e
+
+let nums_from_string str =
+ String.split_on_char ' ' str
+ |> List.filter (fun ch -> String.length ch > 0)
+ |> List.map int_of_string
+
+let rec parse ?(result = 0) lines =
+ match lines with
+ | [] -> result
+ | x :: tail ->
+ let numbers =
+ List.nth (String.split_on_char ':' x) 1
+ |> String.split_on_char '|' |> List.map String.trim
+ |> List.map nums_from_string
+ in
+
+ let winnings = List.nth numbers 0 in
+ let plays = List.nth numbers 1 in
+
+ let k =
+ Int.shift_left 1
+ (List.length
+ (List.map
+ (fun win -> if List.mem win plays = true then 1 else 0)
+ winnings
+ |> List.filter (fun i -> i = 1))
+ - 1)
+ in
+
+ parse tail ~result:(result + k)
+
+let () =
+ let result = read_file input_file |> String.split_on_char '\n' |> parse in
+ Printf.printf "%d\n" result