My yearly advent-of-code solutions
1let filename = "./day_01_input.txt"
2let try_read ic = try Some (input_line ic) with End_of_file -> None
3
4let line_to_ints s =
5 Str.split_delim (Str.regexp " ") s |> List.map int_of_string
6
7let rec read_lines left right ic =
8 match try_read ic with
9 | Some line -> (
10 line_to_ints line |> fun ints ->
11 match ints with
12 | [ a; b ] -> read_lines (a :: left) (b :: right) ic
13 | _ -> failwith "invalid")
14 | None ->
15 close_in ic;
16 (List.sort compare left, List.sort compare right)
17
18let calc_sum left right =
19 List.map2 ( - ) left right |> List.map abs |> List.fold_left ( + ) 0
20
21let calc_sim left right =
22 List.map
23 (fun x -> x * (List.filter (fun y -> x == y) right |> List.length))
24 left
25 |> List.fold_left ( + ) 0
26
27let () =
28 let left, right = open_in filename |> read_lines [] [] in
29 calc_sum left right |> Printf.sprintf "Sum %d" |> print_endline;
30 calc_sim left right |> Printf.sprintf "Part 2 Simularity %d" |> print_endline