diff --git a/lib/common.ml b/lib/common.ml index 7b58be2..ad8ec4e 100644 --- a/lib/common.ml +++ b/lib/common.ml @@ -18,3 +18,18 @@ let get_input year day = | Some lines -> lines | None -> [] ;; + +let of_int_pair s = + String.split_on_chars s ~on:[ ' ' ] + |> List.filter ~f:(fun x -> String.length x > 0) + |> List.map ~f:Int.of_string + |> function + | [ a; b ] -> a, b + | _ -> failwith "invalid format" +;; + +let of_sorted_two_column_int_list input = + List.map ~f:of_int_pair input + |> List.unzip + |> fun (a, b) -> List.sort a ~compare:Int.compare, List.sort b ~compare:Int.compare +;; diff --git a/src/year_2024/day_1.ml b/src/year_2024/day_1.ml index 44abe96..ab266d6 100644 --- a/src/year_2024/day_1.ml +++ b/src/year_2024/day_1.ml @@ -1,4 +1,20 @@ open Core +open Common -let part_1 input = String.concat ~sep:" " input -let part_2 input = String.concat ~sep:" " input +let part_1 input = + let l, r = of_sorted_two_column_int_list input in + (* + let () = + List.iter l ~f:(fun x -> + Out_channel.output_string stdout (Int.to_string x); + print_string " ") + in + *) + List.fold2_exn l r ~init:0 ~f:(fun acc a b -> acc + abs (a - b)) |> string_of_int +;; + +let part_2 input = + let l, r = of_sorted_two_column_int_list input in + List.fold l ~init:0 ~f:(fun acc x -> acc + (x * List.count r ~f:(Int.equal x))) + |> string_of_int +;;