Solve day 1 part 1

This commit is contained in:
Reimar 2024-12-03 21:40:01 +01:00
commit ceac8f51f2
Signed by: Reimar
GPG Key ID: 93549FA07F0AE268
2 changed files with 33 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
day_*.txt

31
day_1.sml Normal file
View File

@ -0,0 +1,31 @@
val file = TextIO.openIn "day_1.txt";
val input = TextIO.inputAll file;
TextIO.closeIn file;
fun sortAsc (l: int list) : int list = ListMergeSort.sort (fn (a, b) => a > b) l
fun sum (l: int list) : int = foldl (fn (a, b) => a + b) 0 l
fun substrToInt(substr: substring) : int = valOf (Int.fromString (Substring.string substr))
val lines = String.tokens (fn (char) => char = #"\n") input
val pairs = map
(fn (line) =>
let val substr = Substring.extract (line, 0, NONE)
in [
substrToInt (Substring.takel Char.isDigit substr),
substrToInt (Substring.taker Char.isDigit substr)
] end
)
lines
val lists = (
sortAsc (map (fn (pair) => hd pair) pairs),
sortAsc (map (fn (pair) => List.last pair) pairs)
)
val distances = ListPair.map (fn (n1, n2) => abs(n1 - n2)) lists
val totalDistance = sum distances