Skip to content

Instantly share code, notes, and snippets.

@milang
Created December 13, 2017 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milang/65f711ba48cc0dfd757ed66053506269 to your computer and use it in GitHub Desktop.
Save milang/65f711ba48cc0dfd757ed66053506269 to your computer and use it in GitHub Desktop.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// 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