-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday01_part02.fs
101 lines (94 loc) · 3.39 KB
/
day01_part02.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
module day01_part02
open System
open AdventOfCode_2016.Modules.LocalHelper
let path = "day01/day01_input.txt"
let getOp (value: string) =
(value.Trim().Substring(0, 1), int(value.Trim().Substring(1)))
let getNewPosition (init: string * int[]) (op: string * int) =
match fst init with
| "N" ->
match fst op with
| "R" ->
let visited =
seq {
for idx in 1..snd op do
yield [|(snd init).[0]; (snd init).[1] + idx|]
} |> List.ofSeq |> List.rev
// visited
("R", visited)
| "L" ->
let visited =
seq {
for idx in 1..snd op do
yield [|(snd init).[0]; (snd init).[1] - idx|]
} |> List.ofSeq |> List.rev
// visited
("L", visited)
| _ -> ("N", [snd init])
| "S" ->
match fst op with
| "R" ->
let visited =
seq {
for idx in 1..snd op do
yield [|(snd init).[0]; (snd init).[1] - idx|]
} |> List.ofSeq |> List.rev
("L", visited)
| "L" ->
let visited =
seq {
for idx in 1..snd op do
yield [|(snd init).[0]; (snd init).[1] + idx|]
} |> List.ofSeq |> List.rev
("R", visited)
| _ -> ("S", [snd init])
| "L" ->
match fst op with
| "R" ->
let visited =
seq {
for idx in 1..snd op do
yield [|(snd init).[0] - idx; (snd init).[1]|]
} |> List.ofSeq |> List.rev
("N", visited)
| "L" ->
let visited =
seq {
for idx in 1..snd op do
yield [|(snd init).[0] + idx; (snd init).[1]|]
} |> List.ofSeq |> List.rev
("S", visited)
| _ -> ("L", [snd init])
| "R" ->
match fst op with
| "R" ->
let visited =
seq {
for idx in 1..snd op do
yield [|(snd init).[0] + idx; (snd init).[1]|]
} |> List.ofSeq |> List.rev
("S", visited)
| "L" ->
let visited =
seq {
for idx in 1..snd op do
yield [|(snd init).[0] - idx; (snd init).[1]|]
} |> List.ofSeq |> List.rev
("N", visited)
| _ -> ("R", [snd init])
|_ -> (fst init, [snd init])
let rec getPosition (ops: (string * int) list) (currentPos: string * int[]) (visited: int[] list)=
match ops with
| [] -> snd currentPos
| head :: tail ->
let newPos = (getNewPosition currentPos head)
let intsersec = visited |> List.tryFind(fun v -> (snd newPos) |> List.exists(fun p -> p = v))
match intsersec with
| Some(found) -> found
| None -> getPosition tail (fst newPos, (snd newPos).Head) (visited @ (snd newPos))
let execute =
let inputLines = GetContentFromFile(path)
let operations = inputLines.Split(',') |> Array.map(fun op -> getOp op) |> List.ofArray
let initPos = ("N", [|0; 0|])
let finalPos = getPosition operations initPos [[|0; 0|]]
Math.Abs(finalPos.[0]) + Math.Abs(finalPos.[1])