52 lines
1.4 KiB
OCaml
52 lines
1.4 KiB
OCaml
open Printf;;
|
|
open String;;
|
|
|
|
let rec build_list in_file =
|
|
try
|
|
let line = input_line in_file in
|
|
line :: build_list(in_file)
|
|
with End_of_file ->
|
|
close_in in_file;
|
|
[]
|
|
|
|
let is_not_empty lst =
|
|
match lst with
|
|
| [] -> false
|
|
| _ -> true
|
|
|
|
let rec parse_list (l1, l2) str =
|
|
let list1 = (List.filter (fun a -> length a != 0) (String.split_on_char ' ' str)) in
|
|
let list_of_int = List.map int_of_string list1 in
|
|
match list_of_int with
|
|
| e1 :: e2 :: _ -> (e1 :: l1, e2 :: l2)
|
|
| _ -> failwith "Not enough ints in a line"
|
|
|
|
let rec count_and_remove value acc lst =
|
|
match lst with
|
|
| n :: tail ->
|
|
if n < value then
|
|
count_and_remove value acc tail
|
|
else if n == value then
|
|
count_and_remove value (acc + 1) tail
|
|
else
|
|
(acc, lst)
|
|
| _ -> (acc, lst)
|
|
|
|
let rec get_list_similarity acc l1 l2 =
|
|
match l1 with
|
|
| n :: tail1 ->
|
|
let (c1, l1_new) = count_and_remove n 1 tail1 in
|
|
let (c2, l2_new) = count_and_remove n 0 l2 in
|
|
get_list_similarity (acc + n * c1 * c2) l1_new l2_new
|
|
| _ -> acc
|
|
|
|
let () =
|
|
let f = open_in "input.txt" in
|
|
let lst = build_list f in
|
|
let (l1, l2) = List.fold_left parse_list ([], []) lst in
|
|
let l1_sorted = List.sort Int.compare l1 in
|
|
let l2_sorted = List.sort Int.compare l2 in
|
|
let result = List.fold_left Int.add 0 (List.map2 (fun a b -> Int.abs(a - b)) l1_sorted l2_sorted) in
|
|
let result2 = get_list_similarity 0 l1_sorted l2_sorted in
|
|
printf "%d\n" result;
|
|
printf "%d\n" result2 |