-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday06_part01.fs
95 lines (80 loc) · 2.92 KB
/
day06_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
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
module day06_part01
open AdventOfCode_2024.Modules
type Direction =
| UP
| DOWN
| RIGHT
| LEFT
type MapDefinition = {
Definition : char [,]
PatrolPos: int array;
PatrolDirection : Direction
Blockers: int array list
}
let getDir(dir: Direction) =
match dir with
| UP -> [| -1; 0 |]
| DOWN -> [| 1; 0 |]
| RIGHT -> [| 0; 1 |]
| LEFT -> [| 0; -1 |]
let turnRight(dir: Direction) =
match dir with
| UP -> RIGHT
| DOWN -> LEFT
| RIGHT -> DOWN
| LEFT -> UP
let parseContent(lines: string array) =
let map = Array2D.create lines.Length lines[0].Length '.'
let patrolPos = [|0; 0|]
let blockers =
[for rIdx in 0..lines.Length-1 do
for cIdx in 0..lines[rIdx].Length-1 do
let value = lines[rIdx][cIdx]
if value = '^' then
patrolPos[0] <- rIdx
patrolPos[1] <- cIdx
if value = '#' then
yield [|rIdx; cIdx|]
map[rIdx, cIdx] <- lines[rIdx][cIdx]
]
{ Definition = map; PatrolPos = patrolPos; PatrolDirection = UP; Blockers = blockers }
let printMap (map: char[,]) =
for row in [0..map.GetUpperBound(0)] do
for column in [0..map.GetUpperBound(1) ] do
printf "%c" map[row, column]
printfn ""
let outOfBoundaries(row: int) (col: int) (maxRows: int) (maxCols: int) =
row >= 0 && row < maxRows && col >= 0 && col < maxCols
let patrol(patrol: MapDefinition) =
let mutable outOfRange = false
let mutable currentDirection = patrol.PatrolDirection
let pos = [|patrol.PatrolPos[0]; patrol.PatrolPos[1]|]
let maxRows = patrol.Definition.GetLength(0)
let maxCols = patrol.Definition.GetLength(1)
let visitedMap = Array2D.create maxRows maxCols '.'
visitedMap[pos[0], pos[1]] <- 'X'
let visited =
[visitedMap[pos[0], pos[1]]] @
[while not outOfRange do
let currentDir = getDir currentDirection
pos[0] <- pos[0] + currentDir[0]
pos[1] <- pos[1] + currentDir[1]
if not (outOfBoundaries pos[0] pos[1] maxRows maxCols) then
outOfRange <- true
else
let mapvalue = patrol.Definition[pos[0], pos[1]]
if mapvalue <> '#' then
if visitedMap[pos[0], pos[1]] <> 'X' then
visitedMap[pos[0], pos[1]] <- 'X'
yield visitedMap[pos[0], pos[1]]
else
pos[0] <- pos[0] - currentDir[0]
pos[1] <- pos[1] - currentDir[1]
currentDirection <- turnRight currentDirection]
(visitedMap, visited.Length)
let execute() =
let path = "day06/day06_input.txt"
let content = LocalHelper.GetLinesFromFile path
let mapDefinition = parseContent content
let (visited, counted) = patrol mapDefinition
counted