-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day19.fs
98 lines (73 loc) · 2.6 KB
/
Day19.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
module aoc24.Day19
open System
open FParsec
let parseInput (input: string array) =
let towels = input[0] |> StringEx.splitS ", "
let arrangements = input[2..]
(towels, arrangements)
let part1 input =
let towels, arrangements = parseInput input
let parser =
let towelTokens = towels |> Array.toList |> List.map pstring
let nextToken, nextTokenRef = createParserForwardedToRef ()
let chainedTowelToken =
towelTokens
|> List.map (fun t -> pipe2 t nextToken (fun a b -> a :: b) |> attempt)
nextTokenRef.Value <- choice [ eof >>% []; choice chainedTowelToken ]
nextToken
let canParse input =
match run parser input with
| Success(res, _, _) ->
dprintfn $"success '{input}': %A{res}"
true
| Failure(msg, _, _) ->
dprintfn ""
dprintfn $"error '{input}': %A{msg}"
false
arrangements |> Array.filter canParse |> Array.length
let part2 input =
let towels, arrangements = parseInput input
let countPossibilities (arrangement: string) =
let rec loop result tails =
let successes =
tails
|> Array.sumBy (fun (count, tail) -> if tail = arrangement.Length then count else 0L)
let nextTails =
tails
|> Array.collect (fun (count, tail) ->
towels
|> Array.choose (fun towel ->
let tailSpan = arrangement.AsSpan(tail)
if MemoryExtensions.StartsWith(tailSpan, towel, StringComparison.Ordinal) then
Some(count, tail + towel.Length)
else
None))
let compactedTails =
nextTails
|> Array.groupBy snd
|> Array.map (fun (key, value) -> (value |> Array.sumBy fst, key))
if nextTails.Length > 0 then
loop (result + successes) compactedTails
else
(result + successes)
loop 0 [| 1, 0 |]
arrangements |> Array.Parallel.sumBy countPossibilities
let run = runReadAllLines part1 part2
module tests =
open Swensen.Unquote
open Xunit
let example =
[| "r, wr, b, g, bwu, rb, gb, br"
""
"brwrr"
"bggr"
"gbbr"
"rrbgbr"
"ubwu"
"bwurrg"
"brgr"
"bbrgwb" |]
[<Fact>]
let ``Part 1 example`` () = part1 example =! 6
[<Fact>]
let ``Part 2 example`` () = part2 example =! 16