From: Ummon Date: Mon, 18 Dec 2017 07:16:48 +0000 (+0100) Subject: Get ride off 'mutable' variables. X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=bec09f2a341a270fae1ba38871eb4bdc796510e5;p=advent_of_code_2017.git Get ride off 'mutable' variables. --- diff --git a/AdventOfCode2017/AdventOfCode2017.fsproj b/AdventOfCode2017/AdventOfCode2017.fsproj index 2fbe84d..57bd951 100644 --- a/AdventOfCode2017/AdventOfCode2017.fsproj +++ b/AdventOfCode2017/AdventOfCode2017.fsproj @@ -37,7 +37,7 @@ AnyCPU bin\$(Configuration)\$(AssemblyName).XML true - 17 + 16 11 diff --git a/AdventOfCode2017/Day16.fs b/AdventOfCode2017/Day16.fs index 8a6d7a6..1a124d7 100644 --- a/AdventOfCode2017/Day16.fs +++ b/AdventOfCode2017/Day16.fs @@ -24,16 +24,13 @@ let parseInput (input : string) : DanceMove list = let dance (size : int) (nb : int) (moves : DanceMove list) : string = let initialState = Array.init size (fun i -> char i + 'a') - let danceFloor = Array.copy initialState - let find c = danceFloor |> Array.findIndex ((=) c) - let swap p1 p2 = - let tmp = danceFloor.[p1] - danceFloor.[p1] <- danceFloor.[p2] - danceFloor.[p2] <- tmp - - let mutable n = nb - while n <> 0 do + let applyMoves (danceFloor : char[]) = + let find c = danceFloor |> Array.findIndex ((=) c) + let swap p1 p2 = + let tmp = danceFloor.[p1] + danceFloor.[p1] <- danceFloor.[p2] + danceFloor.[p2] <- tmp for move in moves do match move with | Spin s -> @@ -47,11 +44,16 @@ let dance (size : int) (nb : int) (moves : DanceMove list) : string = | Partner (a, b) -> swap (find a) (find b) - n <- n - 1 - if danceFloor |=| initialState then - n <- nb % (nb - n) - - String danceFloor - - - + let cycle = + ((0, initialState), Seq.initInfinite id) + ||> Seq.scan ( + fun (_, previous) i -> + let current = previous.[*] + applyMoves current + i + 1, current + ) + |> Seq.takeWhile (fun (i, state) -> i = 0 || not (state |=| initialState)) + |> Seq.map snd + |> Array.ofSeq + + cycle.[nb % cycle.Length] |> String \ No newline at end of file