aboutsummaryrefslogtreecommitdiff
path: root/aoc-2022-dotnet/Day09/Program.fs
blob: df9f040c9b2a753e5e67f700e0e0081ba9b78774 (plain)
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
module Day09

open System.IO
open Common

let directionToVec =
    Vec2
    << 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) -> Seq.replicate (int line[2..]) (directionToVec line[0]))

let moveTail head tail =
    if Vec2.chebyshevDist head tail <= 1 then
        tail
    else
        tail + Vec2.sign (head - tail)

let createRope length = List.replicate length Vec2.zero

let solution ropeLength =
    parseHeadMoves
    >> Seq.scan
        (fun rope headMove ->
            match rope with
            | head :: tail -> List.scan moveTail (head + headMove) tail
            | [] -> [])
        (createRope ropeLength)
    >> Seq.map Seq.last
    >> Util.countDistinct

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