diff options
author | Tomasz Chojnacki <tomaszchojnacki2001@gmail.com> | 2022-12-09 17:28:53 +0100 |
---|---|---|
committer | Tomasz Chojnacki <tomaszchojnacki2001@gmail.com> | 2022-12-09 17:28:53 +0100 |
commit | fd04f2ebd1a4ade35a3e218b7737311ac631fce8 (patch) | |
tree | 5a7fff67ffdb4f413996c80c93567c3ab0d6e182 /aoc-2022-dotnet | |
parent | 65844a7ff88870f1336ccc10ceaba3b4c3bc2a25 (diff) | |
download | gleam_aoc2020-fd04f2ebd1a4ade35a3e218b7737311ac631fce8.tar.gz gleam_aoc2020-fd04f2ebd1a4ade35a3e218b7737311ac631fce8.zip |
Finish day 9
Diffstat (limited to 'aoc-2022-dotnet')
-rw-r--r-- | aoc-2022-dotnet/Day09/Program.fs | 44 | ||||
-rw-r--r-- | aoc-2022-dotnet/README.md | 4 |
2 files changed, 46 insertions, 2 deletions
diff --git a/aoc-2022-dotnet/Day09/Program.fs b/aoc-2022-dotnet/Day09/Program.fs index 178511b..5f49c63 100644 --- a/aoc-2022-dotnet/Day09/Program.fs +++ b/aoc-2022-dotnet/Day09/Program.fs @@ -2,6 +2,50 @@ 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) + +let directionToVec = + Vec2D + << function + | 'U' -> (0, 1) + | 'R' -> (1, 0) + | 'D' -> (0, -1) + | 'L' -> (-1, 0) + | char -> failwithf "Invalid direction: %c" char + +let parseHeadMoves = + Seq.collect (fun (line: string) -> List.replicate (int line[2..]) (directionToVec line[0])) + +let constrainTail head tail = + if Vec2D.chebyshevDist head tail <= 1 then + tail + else + let (Vec2D (dx, dy)) = head - tail + tail + Vec2D(sign dx, sign dy) + +let createRope length = List.replicate length Vec2D.zero + +let solution ropeLength = + parseHeadMoves + >> Seq.scan + (fun rope move -> + match rope with + | h :: t -> List.scan constrainTail (h + move) t + | [] -> []) + (createRope ropeLength) + >> Seq.map Seq.last + >> Set + >> Set.count + let test = File.ReadLines("test.txt") +assert (solution 2 test = 13) +assert (solution 10 test = 1) let input = File.ReadLines("input.txt") +printfn "%d" <| solution 2 input +printfn "%d" <| solution 10 input diff --git a/aoc-2022-dotnet/README.md b/aoc-2022-dotnet/README.md index 9ab58da..a0ce07f 100644 --- a/aoc-2022-dotnet/README.md +++ b/aoc-2022-dotnet/README.md @@ -1,6 +1,6 @@ # Advent of Code 2022 in .NET  - + ## Progress | Day | Part 1 | Part 2 | @@ -13,7 +13,7 @@ | Day 6: Tuning Trouble | 🌟 | 🌟 | | Day 7: No Space Left On Device | 🌟 | 🌟 | | Day 8: Treetop Tree House | 🌟 | 🌟 | -| Day 9: ??? | | | +| Day 9: Rope Bridge | 🌟 | 🌟 | | Day 10: ??? | | | | Day 11: ??? | | | | Day 12: ??? | | | |