diff options
Diffstat (limited to 'day1.fsx')
-rw-r--r-- | day1.fsx | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/day1.fsx b/day1.fsx new file mode 100644 index 0000000..cec57b5 --- /dev/null +++ b/day1.fsx @@ -0,0 +1,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" |