Skip to content

Instantly share code, notes, and snippets.

@tariknz
Last active December 4, 2018 00:38
Show Gist options
  • Select an option

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

Select an option

Save tariknz/b040f4f9b6086cd786da0688186e6cf0 to your computer and use it in GitHub Desktop.
open System.IO
open System.Text.RegularExpressions
type Claim = { id: string; pos: int * int; size: int * int}
let (|Regex|_|) pattern input = // snippet to make a regex function and return capturing groups
let m = Regex.Match(input, pattern)
if m.Success then Some(List.tail [ for g in m.Groups -> g.Value ])
else None
let claimParser line =
match line with
| Regex "^#(\d+) @ (\d+),(\d+): (\d+)x(\d+)" [ id; top; left; width; height] ->
Some ({
id = id;
pos = (int top, int left);
size = (int width, int height) })
| _ -> None
let claims = File.ReadLines("day-3.txt") |> Seq.choose claimParser
// getting max values so we can create a big as fabric to fit everyone
let maxWidth, maxHeight =
claims
|> Seq.map (fun claim -> (fst claim.size), (snd claim.size))
|> (fun size -> (Seq.maxBy fst size |> fst), (Seq.maxBy snd size |> snd))
let maxX, maxY =
claims
|> Seq.map (fun claim -> fst claim.pos, snd claim.pos)
|> (fun pos -> (Seq.maxBy fst pos |> fst), (Seq.maxBy snd pos |> snd))
|> (fun pos -> fst pos + maxWidth, snd pos + maxHeight)
let fabric = Array2D.create maxX maxY []
claims
|> Seq.iter (fun claim ->
for y in [fst claim.pos .. (fst claim.pos + fst claim.size) - 1] do
for x in [snd claim.pos .. (snd claim.pos + snd claim.size) - 1] do
fabric.[x, y] <- List.append [claim.id] fabric.[x, y]) // append claim ids to the square
let overlappingBlocks: seq<seq<string>> =
fabric
|> Seq.cast // flattens Array2D to seq
|> Seq.filter (fun ids -> Seq.length ids > 1)
// part 1
overlappingBlocks
|> Seq.length
|> printfn "%A"
// part 2
let overlappingClaims =
overlappingBlocks
|> Seq.concat
|> Seq.distinct // flatten array and get only distinct claim ids
claims
|> Seq.map (fun claim -> claim.id)
|> Seq.except overlappingClaims // claim ids not exist in the overlap
|> printfn "%A"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment