Created
December 13, 2017 15:58
-
-
Save milang/65f711ba48cc0dfd757ed66053506269 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 | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
type Layer = { index: int; depth: int; period: int } | |
let parse filename = | |
File.ReadAllLines(filename) | |
|> Seq.map (fun line -> | |
let parts = line.Split(':') | |
let depth = int parts.[1] | |
{ index = int parts.[0]; depth = depth; period = (depth - 1) * 2 }) // period: how often this layer visits zero | |
|> List.ofSeq | |
let data = parse "queries/Advent/Advent2017-day13.txt" | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
// Problem A | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
let calculateSeverity layers startingTime = | |
layers | |
|> List.map | |
(fun layer -> | |
let layerPosition = (startingTime + layer.index) % layer.period | |
if layerPosition = 0 then (layer.index * layer.depth) else 0) | |
|> List.sum | |
(calculateSeverity data 0).Dump("Severity with immediate entry"); | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
// Problem B | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
let delay = | |
Seq.initInfinite id | |
|> Seq.map | |
(fun delay -> | |
let firstInterception = | |
data | |
|> List.tryFind // is there a layer that is at position 0 given the "delay"? | |
(fun layer -> | |
let layerPosition = (delay + layer.index) % layer.period | |
layerPosition = 0) | |
match firstInterception with | Some _ -> -1 | None -> delay) | |
|> Seq.find ((<) 0) // find first positive result (i < 0) | |
delay.Dump("Delay to not be caught") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment