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
|
open System.IO
let lines = (File.ReadAllText "day1.txt").Split ", "
let rec move (steps: string[]) (dir: int) (x: int) (y: int): int =
if (Array.length steps) = 0 then abs x + abs y
else
let instDir = steps[0][0]
let instLen = steps[0][1..] |> int
let newDir =
match instDir with
| 'R' -> (dir + 1) % 4
| 'L' -> (((dir - 1) % 4) + 4) % 4
| _ -> -500 // will never get to this point but the compiler yells at me otherwise
let (newX, newY) =
match newDir with
| 0 -> (x, y + instLen)
| 1 -> (x + instLen, y)
| 2 -> (x, y - instLen)
| 3 -> (x - instLen, y)
| _ -> (-500, -500) // again will never reach here
move steps[1..] newDir newX newY
let rec move2 (steps: string[]) (dir: int) (x: int) (y: int) (visited: Set<int * int>): int =
let instDir = steps[0][0]
let instLen = steps[0][1..] |> int
let newDir =
match instDir with
| 'R' -> (dir + 1) % 4
| 'L' -> (((dir - 1) % 4) + 4) % 4
| _ -> -500
let newVisited =
match newDir with
| 0 -> set [for newY in seq {y+1 .. y+instLen} do yield (x, newY)]
| 1 -> set [for newX in seq {x+1 .. x+instLen} do yield (newX, y)]
| 2 -> set [for newY in seq {y-1 .. -1 .. y-instLen} do yield (x, newY)]
| 3 -> set [for newX in seq {x-1 .. -1 .. x-instLen} do yield (newX, y)]
| _ -> Set.empty
let diff = Set.intersect visited newVisited
if (Set.count diff) > 0 then
let pointList = [for point in diff do yield point]
let (pointX, pointY) = pointList[0] // assume there is only one intersection at a time
abs pointX + abs pointY
else
let (newX, newY) =
match newDir with
| 0 -> (x, y + instLen)
| 1 -> (x + instLen, y)
| 2 -> (x, y - instLen)
| 3 -> (x - instLen, y)
| _ -> (-500, -500)
move2 steps[1..] newDir newX newY (Set.union visited newVisited)
move lines 0 0 0 |> printfn "%A"
move2 lines 0 0 0 Set.empty |> printfn "%A"
|