namespace AdventOfCode2023 open System open System.Collections.Generic open System.Globalization [] module Day12 = let rec solve (line : ReadOnlySpan) (groups : IReadOnlyList) (currentGroupIndex : int) = match line.[0] with | '#' -> if currentGroupIndex >= groups.Count then 0 else let mutable isOk = true for i = 1 to groups.[currentGroupIndex] - 1 do if isOk && line.[i] <> '#' && line.[i] <> '?' then isOk <- false if not isOk then 0 else if line.[groups.[currentGroupIndex]] = '#' then 0 else solve (line.Slice (groups.[currentGroupIndex] + 1)) groups (currentGroupIndex + 1) | '.' -> solve (line.Slice 1) groups currentGroupIndex | '?' -> let ifDot = solve (line.Slice 1) groups currentGroupIndex let ifHash = if currentGroupIndex >= groups.Count then 0 else let mutable isOk = true for i = 1 to groups.[currentGroupIndex] - 1 do if isOk && line.[i] <> '#' && line.[i] <> '?' then isOk <- false if not isOk then 0 else if line.[groups.[currentGroupIndex]] = '#' then 0 else solve (line.Slice (groups.[currentGroupIndex] + 1)) groups (currentGroupIndex + 1) ifDot + ifHash | _ -> if currentGroupIndex = groups.Count then 1 else 0 let part1 (s : string) = use mutable lines = StringSplitEnumerator.make '\n' s let mutable answer = 0 let arr = ResizeArray () for line in lines do if not line.IsEmpty then arr.Clear () use ints = StringSplitEnumerator.make' ',' (line.Slice (line.IndexOf ' ' + 1)) for int in ints do arr.Add (Int32.Parse (int, NumberStyles.None, CultureInfo.InvariantCulture)) let solved = solve line arr 0 answer <- answer + solved answer let part2 (s : string) = use mutable lines = StringSplitEnumerator.make '\n' s -1