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"