summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--day9.fsx36
1 files changed, 36 insertions, 0 deletions
diff --git a/day9.fsx b/day9.fsx
new file mode 100644
index 0000000..de64fea
--- /dev/null
+++ b/day9.fsx
@@ -0,0 +1,36 @@
+open System.IO
+open System.Text.RegularExpressions
+
+let (|Regex|_|) input =
+    let m = Regex.Match(input, "^(?:\((\w+?)\))(.*)")
+    if m.Success then Some(List.tail [for g in m.Groups -> g.Value])
+    else None
+
+let splitPattern str =
+    match str with 
+    | Regex [marker; rest] -> marker, rest
+    | _ -> "", ""
+
+let rec decrypt str =
+    if str = "" then ""
+    else
+        let marker, rest = splitPattern str
+        if marker = "" then string str[0] + decrypt str[1..]
+        else
+            let nums = marker.Split 'x' |> Array.map int
+            let start, count = (min nums[0] (String.length rest)), nums[1]
+            String.replicate count rest[..start-1] + decrypt rest[start..]
+
+let rec decryptLength str =
+    if str = "" then bigint 0
+    else
+        let marker, rest = splitPattern str
+        if marker = "" then bigint 1 + decryptLength str[1..]
+        else
+            let nums = marker.Split 'x' |> Array.map int
+            let start, count = (min nums[0] (String.length rest)), nums[1]
+            bigint count * decryptLength rest[..start-1] + decryptLength rest[start..]
+
+let lines = File.ReadLines "day9.txt"
+lines |> Seq.map decrypt |> Seq.map String.length |> Seq.reduce (+) |> printfn "%d"
+lines |> Seq.map decryptLength |> Seq.reduce (+) |> printfn "%A"