Solve day 2 in SML

This commit is contained in:
Reimar 2023-12-26 18:24:49 +01:00
parent e9c8abef6a
commit 7085417b12

59
day_2.sml Normal file
View File

@ -0,0 +1,59 @@
val file = TextIO.openIn "day_2.txt";
val input = TextIO.inputAll file;
TextIO.closeIn file;
fun equals a b = a = b
fun non f x = not (f x)
val maxRed = 12
val maxGreen = 13
val maxBlue = 14
val possibleGames =
let val lines = String.tokens (equals #"\n") input
in
List.filter
(fn line =>
let
val game = List.last (String.tokens (equals #":") line)
val rounds = String.tokens (equals #";") game
val rounds = map
(fn round => String.extract (round, 1, NONE))
rounds
in
List.all
(fn round =>
let
val reveals = String.tokens (non Char.isAlphaNum) round
val revealPairs = ListPair.zip (
(List.filter (fn elem => (Int.fromString elem) = NONE) reveals),
(List.mapPartial Int.fromString reveals)
)
in
List.all
(fn revealPair =>
(#2 revealPair) <= (case #1 revealPair of
"red" => maxRed
| "green" => maxGreen
| "blue" => maxBlue
))
revealPairs
end
)
rounds
end
)
lines
end
val result = List.foldl
(fn (game, acc) =>
let
val title = List.hd (String.tokens (equals #":") game)
val id = Option.valOf (Int.fromString (String.extract (title, 5, NONE)))
in
acc + id
end
)
0
possibleGames