Skip to content

Instantly share code, notes, and snippets.

@tariknz
Last active December 6, 2018 07:14
Show Gist options
  • Select an option

  • Save tariknz/bd9cc550f258ab917c3ca7ecce6af28d to your computer and use it in GitHub Desktop.

Select an option

Save tariknz/bd9cc550f258ab917c3ca7ecce6af28d to your computer and use it in GitHub Desktop.
open System.IO
open System
let input = File.ReadLines("2018-day-6.txt")
type PlaceDistance = { id: int; distance: int; location: int * int }
let coords =
input
|> Seq.map (fun i -> i.Split(','))
|> Seq.map (fun i -> int i.[0], int i.[1])
// check max X and Y coords to draw out our map
let maxX = coords |> Seq.maxBy fst |> fun i -> fst i
let maxY = coords |> Seq.maxBy snd |> fun i -> snd i
let map = Array2D.create (maxX + 1) (maxY + 1) -1
// calculate distance between two points
let distance (startPos: int * int, endPos: int * int) =
Math.Abs(fst startPos - fst endPos) +
Math.Abs(snd startPos - snd endPos)
// iterate the map
for x in [0 .. maxX] do
for y in [0 .. maxY] do
let distances =
coords
|> Seq.mapi (fun i place -> { id = i; distance = distance ((x,y), place); location = place; } )
|> Seq.sortBy (fun loca -> loca.distance)
// check if closest and second closest are equal, then there is an overlap
let first, second = distances |> Seq.pairwise |> Seq.head
if first.distance <> second.distance then map.[x, y] <- first.id
// remove all places that appear on the left edge, top edge, right edge, and bottom edge
let infinites =
map.[0, 0 .. maxY] // top
|> Array.append map.[maxX, 0 .. maxY] // bottom
|> Array.append map.[0.. maxX, 0] // left
|> Array.append map.[0.. maxX, maxY] // right
|> Array.filter (fun i -> i <> -1) // ignore -1
|> Array.distinct
map
|> Seq.cast // flatten
|> Seq.filter (fun i -> not(Array.contains i infinites))
|> Seq.countBy id
|> Seq.sortByDescending snd
|> Seq.head
|> printfn "%A"
// part 2
let map2 = Array2D.zeroCreate (maxX + 1) (maxY + 1)
for x in [0 .. maxX] do
for y in [0 .. maxY] do
let distances =
coords
|> Seq.map (fun place -> distance ((x,y), place))
|> Seq.sum
map2.[x, y] <- distances
map2
|> Seq.cast
|> Seq.filter (fun d -> d < 10000)
|> Seq.length
|> printfn "%A"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment