From bec09f2a341a270fae1ba38871eb4bdc796510e5 Mon Sep 17 00:00:00 2001 From: Ummon Date: Mon, 18 Dec 2017 08:16:48 +0100 Subject: [PATCH] Get ride off 'mutable' variables. --- AdventOfCode2017/AdventOfCode2017.fsproj | 2 +- AdventOfCode2017/Day16.fs | 36 +++++++++++++----------- 2 files changed, 20 insertions(+), 18 deletions(-) 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 -- 2.45.2