-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay10.fs
136 lines (111 loc) · 3.42 KB
/
Day10.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
namespace Adventofcode2021
module Day10 =
open System.Collections.Generic
[<Literal>]
let InputFile = "Day10Input.txt"
let scoreCorrupted =
function
| ')' -> 3
| ']' -> 57
| '}' -> 1197
| '>' -> 25137
| _ -> failwith "unknown char"
let isCorrupted (s: string) =
let stack = Stack<char>()
let rec helper a =
if Array.isEmpty a then
0
else
let c = Array.head a
match c with
| '('
| '['
| '{'
| '<' ->
stack.Push c
helper (Array.tail a)
| ')'
| ']'
| '}'
| '>' ->
let opener = stack.Pop()
match opener, c with
| '(', ')'
| '[', ']'
| '{', '}'
| '<', '>' -> helper (Array.tail a)
| _ -> scoreCorrupted c
| _ -> failwith "unknown char"
s.ToCharArray() |> helper
let day10 () =
InputFile
|> System.IO.File.ReadAllLines
|> Array.map isCorrupted
|> Array.sum
let autoComplete (stack: Stack<char>) =
let rec helper missing =
if stack.Count = 0 then
missing
else
let opener = stack.Pop()
let m =
match opener with
| '(' -> ')'
| '[' -> ']'
| '{' -> '}'
| '<' -> '>'
| _ -> failwith "bad state"
let missing' = Array.append missing [| m |]
helper missing'
helper Array.empty
let complete (s: string) =
let stack = Stack<char>()
let rec helper a =
if Array.isEmpty a then
autoComplete stack
else
let c = Array.head a
match c with
| '('
| '['
| '{'
| '<' ->
stack.Push c
helper (Array.tail a)
| ')'
| ']'
| '}'
| '>' ->
let opener = stack.Pop()
match opener, c with
| '(', ')'
| '[', ']'
| '{', '}'
| '<', '>' -> helper (Array.tail a)
| _ -> failwith "bad state"
| _ -> failwith "unknown char"
s.ToCharArray() |> helper
let scoreCompletion a =
let rec helper s a =
if Array.isEmpty a then
s
else
let c = Array.head a
let points =
match c with
| ')' -> 1L
| ']' -> 2L
| '}' -> 3L
| '>' -> 4L
| _ -> failwith "bad state"
let s' = 5L * s + points
helper s' (Array.tail a)
helper 0L a
let day10Part2 () =
InputFile
|> System.IO.File.ReadAllLines
|> Array.filter (fun s -> s |> isCorrupted = 0)
|> Array.map complete
|> Array.map scoreCompletion
|> Array.sort
|> fun a -> a |> Array.item (a.Length / 2)