WIP refactor day 3
This commit is contained in:
parent
5b21b1db58
commit
70c49f3d3c
40
day_3.sml
40
day_3.sml
@ -1,30 +1,36 @@
|
|||||||
|
datatype instruction = NOOP | DO | DONT | MUL of (int * int)
|
||||||
|
|
||||||
fun numberAt (i : int) = fn (s : string) =>
|
fun numberAt (i : int) = fn (s : string) =>
|
||||||
if i >= String.size s then NONE
|
if i >= String.size s then NONE
|
||||||
else SOME (Substring.takel Char.isDigit (Substring.extract (s, i, NONE)))
|
else SOME (Substring.takel Char.isDigit (Substring.extract (s, i, NONE)))
|
||||||
|
|
||||||
fun substrToInt (n : substring) = valOf (Int.fromString (Substring.string n))
|
fun startsWith (needle : string, haystack : string, pos : int) =
|
||||||
|
size haystack > pos + size needle andalso String.substring (haystack, pos, size needle) = needle
|
||||||
|
|
||||||
fun sum (l : int list) : int = foldl (op +) 0 l
|
fun substrToInt (n : substring) = valOf (Int.fromString (Substring.string n))
|
||||||
|
|
||||||
val file = TextIO.openIn "day_3.txt"
|
val file = TextIO.openIn "day_3.txt"
|
||||||
val input = TextIO.inputAll file;
|
val input = TextIO.inputAll file;
|
||||||
TextIO.closeIn file;
|
TextIO.closeIn file;
|
||||||
|
|
||||||
val instructions = List.tabulate ((size input), (fn i =>
|
val instructions = List.tabulate ((size input), (fn i =>
|
||||||
let
|
if startsWith ("do()", input, i) then DO
|
||||||
val n1 = numberAt (i + 4) input
|
else if startsWith ("don't()", input, i) then DONT
|
||||||
val n2 = Option.mapPartial (fn n => numberAt (i + 5 + Substring.size n) input) n1
|
else
|
||||||
in
|
let
|
||||||
if isSome n1 andalso isSome n2 andalso
|
val n1 = numberAt (i + 4) input
|
||||||
String.substring (input, i, 4) = "mul(" andalso
|
val n2 = Option.mapPartial (fn n => numberAt (i + 5 + Substring.size n) input) n1
|
||||||
String.sub (input, i + 4 + Substring.size (valOf n1)) = #"," andalso
|
in
|
||||||
String.sub (input, i + 5 + Substring.size (valOf n1) + Substring.size (valOf n2)) = #")"
|
case (n1, n2) of
|
||||||
then SOME (n1, n2) else NONE
|
(SOME(a), SOME(b)) =>
|
||||||
end))
|
if
|
||||||
|
startsWith ("mul(", input, i) andalso
|
||||||
|
String.sub (input, i + 4 + Substring.size a) = #"," andalso
|
||||||
|
String.sub (input, i + 5 + Substring.size a + Substring.size b) = #")"
|
||||||
|
then MUL (substrToInt a, substrToInt b) else NOOP
|
||||||
|
| _ => NOOP
|
||||||
|
end
|
||||||
|
))
|
||||||
|
|
||||||
val instructions = List.mapPartial
|
val result = foldl (fn (ins, v) => case ins of MUL (a, b) => v + a + b | _ => v) 0 instructions
|
||||||
(fn (num) => case num of SOME (SOME x, SOME y) => SOME (substrToInt x, substrToInt y) | _ => NONE)
|
|
||||||
instructions
|
|
||||||
|
|
||||||
val result = sum (map (op *) instructions)
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user