69 lines
2.0 KiB
OCaml
69 lines
2.0 KiB
OCaml
open Printf;;
|
|
|
|
let rec list_of_lines in_file =
|
|
try
|
|
let line = input_line in_file in
|
|
line :: list_of_lines(in_file)
|
|
with End_of_file ->
|
|
close_in in_file;
|
|
[]
|
|
|
|
let is_not_empty lst =
|
|
match lst with
|
|
| [] -> false
|
|
| _ -> true
|
|
|
|
let rec parse_int_list str =
|
|
let list1 = (List.filter (fun a -> String.length a != 0) (String.split_on_char ' ' str)) in
|
|
List.map int_of_string list1
|
|
|
|
let rec int_list_diff int_list =
|
|
match int_list with
|
|
| e1 :: e2 :: tail -> e2 - e1 :: int_list_diff (e2 :: tail)
|
|
| _ -> []
|
|
|
|
let list_diffs_safe diff_list =
|
|
match diff_list with
|
|
| n :: tail ->
|
|
if n > 0 then
|
|
List.for_all (fun x -> x >= 1 && x <= 3) diff_list
|
|
else if n < 0 then
|
|
List.for_all (fun x -> x >= -3 && x <= -1) diff_list
|
|
else
|
|
false
|
|
| _ -> true
|
|
|
|
let rec list_diff_safe_with_tolerance_inner last condition tol diff_list =
|
|
match diff_list with
|
|
| x :: tail ->
|
|
if condition x then
|
|
list_diff_safe_with_tolerance_inner x condition tol tail
|
|
else if tol then
|
|
match tail with
|
|
| x2 :: tail2 ->
|
|
list_diff_safe_with_tolerance_inner 0 condition false (x + x2 :: tail2)
|
|
|| list_diff_safe_with_tolerance_inner 0 condition false (last + x :: tail)
|
|
| _ -> true
|
|
else
|
|
false
|
|
| _ -> true
|
|
|
|
let list_diff_safe_with_tolerance diff_list =
|
|
if list_diff_safe_with_tolerance_inner 0 (fun x -> x >= 1 && x <= 3) true diff_list
|
|
|| list_diff_safe_with_tolerance_inner 0 (fun x -> x >= -3 && x <= -1) true diff_list then
|
|
true
|
|
else
|
|
match diff_list with
|
|
| _ :: tail -> list_diffs_safe tail
|
|
| _ -> true
|
|
|
|
|
|
let () =
|
|
let f = open_in "input.txt" in
|
|
let lines = list_of_lines f in
|
|
let diffs = List.map (fun a -> int_list_diff @@ parse_int_list a) lines in
|
|
let count = List.fold_left (fun acc l -> if list_diffs_safe l then acc + 1 else acc) 0 diffs in
|
|
let count2 = List.fold_left (fun acc l -> if list_diff_safe_with_tolerance l then acc + 1 else acc) 0 diffs in
|
|
printf "%d\n" count;
|
|
printf "%d\n" count2
|