Created
December 20, 2017 07:49
-
-
Save milang/f60a253dc431035a4cd6581d4d3be1e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
// Input data | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
let findProgram name programs = programs |> Array.findIndex ((=) name) | |
let spin count programs = | |
let offset = count % (Array.length programs) | |
if offset = 0 then programs | |
else | |
programs | |
|> Array.permute | |
(fun index -> (index + offset) % (Array.length programs)) | |
let exchange posA posB (programs: char array) = | |
let tmp = programs.[posA] | |
programs.[posA] <- programs.[posB] | |
programs.[posB] <- tmp | |
programs | |
let partner programA programB programs = | |
exchange (findProgram programA programs) (findProgram programB programs) programs | |
let parse filename = | |
File.ReadAllText(filename).Split(',') | |
|> Seq.map | |
(fun spec -> | |
match spec.[0] with | |
| 's' -> spin (spec.Substring(1) |> int) | |
| 'x' -> | |
let split = spec.IndexOf "/" | |
exchange (spec.Substring(1, (split-1)) |> int) (spec.Substring(split+1) |> int) | |
| 'p' -> | |
partner spec.[1] spec.[3] | |
| _ -> raise (InvalidOperationException "Unknown dance move")) | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
// Problem A | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
let afterDance = | |
parse "queries/Advent/Advent2017-day16.txt" | |
|> Seq.fold | |
(fun p op -> op p) | |
({'a'..'p'} |> Array.ofSeq) | |
(String.Join("", afterDance)).Dump("After single dance") | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
// Problem B | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
let operations = | |
parse "queries/Advent/Advent2017-day16.txt" | |
|> List.ofSeq | |
// dumped first 1000 results into a text file, noticed that | |
// sequence is repeated with period 60 | |
let afterLongDance = | |
{ 1..(1000000000 % 60) } | |
|> Seq.fold | |
(fun programs _ -> | |
operations | |
|> Seq.fold (fun p op -> op p) programs) | |
({'a'..'p'} |> Array.ofSeq) | |
(String.Join("", afterLongDance)).Dump("After billion dances") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment