-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday21_part01.fs
63 lines (51 loc) · 1.88 KB
/
day21_part01.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
module day21_part01
open System
open AdventOfCode_2023.Modules
open FSharpx.Collections
type Coord = {
Row: int
Col: int
}
let numOfDirs = 4
let rowDirs = [| -1; 0; 1; 0|]
let colDirs = [| 0; 1; 0; -1 |]
let border = Int32.MaxValue / 4
let parseInput (input: string list) =
let rows = input.Length
let cols = input.[0].Length
let grid = Array2D.create rows cols '.'
for row in 0..rows-1 do
for col in 0..cols-1 do
grid.[row, col] <- input.[row].[col]
grid
let execute =
let path = "day21/day21_input.txt"
let map = LocalHelper.GetLinesFromFile path |> Seq.toList |> parseInput
let maxRows = map.GetLength(0)
let maxCols = map.GetLength(1)
let distances = Array2D.create maxRows maxCols 0
let mutable coords = Queue.empty<Coord>
let addCoord (row: int) (col: int) (dis: int) =
distances[row, col] <- dis
coords <- (Queue.conj { Row = row; Col = col } coords)
let isValidCoord (row: int) (col: int) =
row >= 0 && row < maxRows &&
col >= 0 && col < maxCols &&
map.[row, col] <> '#' && distances[row, col] = border
for row in 0..maxRows - 1 do
for col in 0..maxCols - 1 do
distances[row, col] <- border
if map[row, col] = 'S' then
addCoord row col 0
while not (Queue.isEmpty coords) do
let (coord, coords') = Queue.uncons coords
coords <- coords'
let current = distances.[coord.Row, coord.Col]
for dirIdx in 0..numOfDirs - 1 do
let newRow = coord.Row + rowDirs[dirIdx]
let newCol = coord.Col + colDirs[dirIdx]
if isValidCoord newRow newCol then
addCoord newRow newCol (current + 1)
let steps = 64
let flatted = distances |> Seq.cast<int> |> Seq.toArray
flatted |> Array.filter(fun d -> d <= steps && d % 2 = 0) |> Array.length