summary refs log blame commit diff stats
path: root/day1.fsx
blob: cec57b5b424a462077060acc0944cc6815fad27d (plain) (tree)

























































                                                                                              
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"