Skip to content

Instantly share code, notes, and snippets.

@kiyov09
Last active November 22, 2023 22:52
Show Gist options
  • Save kiyov09/374f563f2e78718985b3245faaf547c6 to your computer and use it in GitHub Desktop.
Save kiyov09/374f563f2e78718985b3245faaf547c6 to your computer and use it in GitHub Desktop.
OCaml solution for AoC 2022 - Day 1
(**
AoC 2022
*)
module Day1 = struct
let input_file = "./inputs/day1/input.txt"
(** Read from a channel till there's no more to read *)
let read_all ch =
let rec aux acc ch =
match In_channel.input_line ch with
| None -> List.rev acc
| Some s -> aux ( s :: acc ) ch
in
aux [] ch
;;
(** Read all lines from a file given its path *)
let read_input input_file = open_in input_file |> read_all
(** This will give me the elements in revese order but
it doesn't matter in this case *)
let take n lst =
let rec aux n acc = function
| [] -> acc
| _ when n = 0 -> acc
| hd :: tl -> aux (n - 1) (hd :: acc) tl
in
aux n [] lst
;;
(** Common logic for both exercises *)
let common =
let fold_fn acc line =
match line with
| "" -> 0 :: acc
| curr when List.length acc = 0 -> [int_of_string curr]
| curr -> begin
let hd = List.hd acc in
let tl = List.tl acc in
hd + int_of_string curr :: tl
end
in
read_input input_file
|> List.fold_left fold_fn []
|> List.sort Int.compare
|> List.rev
;;
let part1 = common |> take 1 |> List.hd
let part2 = common |> take 3 |> List.fold_left ( + ) 0
end
let () =
Printf.printf "Part 1: %d\n" Day1.part1;
Printf.printf "Part 2: %d\n" Day1.part2
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment