2024-12-04 16:56:12 +00:00
|
|
|
fun deleteNth (l : int list, n : int) = List.take (l, n) @ List.drop (l, n + 1)
|
|
|
|
|
|
|
|
fun isDecreasing (l : int list) =
|
2024-12-05 15:40:10 +00:00
|
|
|
ListPair.all (fn (a, b) => b < a andalso b >= a - 3) (l, tl l)
|
2024-12-04 16:04:52 +00:00
|
|
|
|
2024-12-04 16:56:12 +00:00
|
|
|
fun isIncreasing (l : int list) =
|
2024-12-05 15:40:10 +00:00
|
|
|
ListPair.all (fn (a, b) => b > a andalso b <= a + 3) (l, tl l)
|
2024-12-04 16:04:52 +00:00
|
|
|
|
2024-12-04 16:56:12 +00:00
|
|
|
fun withTolerance (f : (int list) -> bool) = fn (l : int list) =>
|
2024-12-05 15:40:10 +00:00
|
|
|
let val withRemoved = List.tabulate (List.length l, fn (i) => deleteNth (l, i))
|
|
|
|
in List.exists f withRemoved end
|
2024-12-04 16:56:12 +00:00
|
|
|
|
2024-12-04 16:04:52 +00:00
|
|
|
val file = TextIO.openIn "day_2.txt"
|
|
|
|
val input = TextIO.inputAll file;
|
|
|
|
TextIO.closeIn file;
|
|
|
|
|
|
|
|
val lines = String.tokens (fn (char) => char = #"\n") input
|
|
|
|
|
|
|
|
val reports = map
|
2024-12-05 15:40:10 +00:00
|
|
|
(fn (line) =>
|
|
|
|
let val numbers = String.tokens Char.isSpace line
|
|
|
|
in map (fn (n) => valOf (Int.fromString n)) numbers end
|
|
|
|
)
|
|
|
|
lines
|
2024-12-04 16:04:52 +00:00
|
|
|
|
2024-12-04 16:56:12 +00:00
|
|
|
(* Part 1 *)
|
|
|
|
|
2024-12-04 16:04:52 +00:00
|
|
|
val safeReports = List.filter (fn (report) => isDecreasing report orelse isIncreasing report) reports
|
|
|
|
|
|
|
|
val safeAmount = List.length safeReports
|
|
|
|
|
2024-12-04 16:56:12 +00:00
|
|
|
(* Part 2 *)
|
|
|
|
|
|
|
|
val toleratedReports = List.filter
|
2024-12-05 15:40:10 +00:00
|
|
|
(fn (report) => withTolerance isDecreasing report orelse withTolerance isIncreasing report)
|
|
|
|
reports
|
2024-12-04 16:56:12 +00:00
|
|
|
|
|
|
|
val toleratedAmount = List.length toleratedReports
|
|
|
|
|