diff options
Diffstat (limited to 'aoc-2022-dotnet/Day09/Program.fs')
-rw-r--r-- | aoc-2022-dotnet/Day09/Program.fs | 28 |
1 files changed, 10 insertions, 18 deletions
diff --git a/aoc-2022-dotnet/Day09/Program.fs b/aoc-2022-dotnet/Day09/Program.fs index 5f49c63..df9f040 100644 --- a/aoc-2022-dotnet/Day09/Program.fs +++ b/aoc-2022-dotnet/Day09/Program.fs @@ -1,16 +1,10 @@ module Day09 open System.IO - -type Vec2D = - | Vec2D of int * int - static member zero = Vec2D(0, 0) - static member (+)(Vec2D (x1, y1), Vec2D (x2, y2)) = Vec2D(x1 + x2, y1 + y2) - static member (-)(Vec2D (x1, y1), Vec2D (x2, y2)) = Vec2D(x1 - x2, y1 - y2) - static member chebyshevDist (Vec2D (x1, y1)) (Vec2D (x2, y2)) = max (abs <| x2 - x1) (abs <| y2 - y1) +open Common let directionToVec = - Vec2D + Vec2 << function | 'U' -> (0, 1) | 'R' -> (1, 0) @@ -19,28 +13,26 @@ let directionToVec = | char -> failwithf "Invalid direction: %c" char let parseHeadMoves = - Seq.collect (fun (line: string) -> List.replicate (int line[2..]) (directionToVec line[0])) + Seq.collect (fun (line: string) -> Seq.replicate (int line[2..]) (directionToVec line[0])) -let constrainTail head tail = - if Vec2D.chebyshevDist head tail <= 1 then +let moveTail head tail = + if Vec2.chebyshevDist head tail <= 1 then tail else - let (Vec2D (dx, dy)) = head - tail - tail + Vec2D(sign dx, sign dy) + tail + Vec2.sign (head - tail) -let createRope length = List.replicate length Vec2D.zero +let createRope length = List.replicate length Vec2.zero let solution ropeLength = parseHeadMoves >> Seq.scan - (fun rope move -> + (fun rope headMove -> match rope with - | h :: t -> List.scan constrainTail (h + move) t + | head :: tail -> List.scan moveTail (head + headMove) tail | [] -> []) (createRope ropeLength) >> Seq.map Seq.last - >> Set - >> Set.count + >> Util.countDistinct let test = File.ReadLines("test.txt") assert (solution 2 test = 13) |