summaryrefslogtreecommitdiff
path: root/ocaml/lib/year2024/day02/part01.ml
blob: 32d7ab8572219819102ce68917914587274288d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
(* Day 2: Part 1 *)

type level = int
type reports = level list list

let rec compare_report_levels_helper comparison prev report =
  match report with
  | [] -> true
  | h :: t -> comparison prev h && compare_report_levels_helper comparison h t

let compare_report_levels comparison report =
  match report with
  | [] -> true
  | h :: t -> compare_report_levels_helper comparison h t

let all_increasing report = compare_report_levels ( < ) report
let all_decreasing report = compare_report_levels ( > ) report

let at_least_one report =
  compare_report_levels (fun prev curr -> prev <> curr) report

let at_most_three report =
  compare_report_levels (fun prev curr -> abs (prev - curr) <= 3) report

let check_report_safety report =
  if not (all_increasing report || all_decreasing report) then false
  else if not (at_least_one report && at_most_three report) then false
  else true

let rec count_safe_reports acc lst =
  match lst with
  | [] -> acc
  | h :: t ->
      if h then count_safe_reports (acc + 1) t else count_safe_reports acc t

let solve reports =
  reports |> List.map check_report_safety |> count_safe_reports 0

let line_to_report line =
  line |> String.split_on_char ' ' |> List.map int_of_string

let lines_to_reports lines = List.map line_to_report lines