Repository navigation
Expand file tree
/
Copy pathday09.kk
More file actions
54 lines (47 loc) · 2.01 KB
/
Copy pathday09.kk
File metadata and controls
54 lines (47 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import util/prelude
fun parse-input()
get-input-lines()
.map(_.split(",").map(_.parse-int.unjust))
.map(fn (a) (a[0].unjust, a[1].unjust))
fun areas-sorted(coords: list<(int, int)>)
var res: list<(int, (int, int), (int, int))> := Nil
coords.foreach-indexed fn (i, (ax, ay))
coords.drop(i + 1).foreach-indexed() fn (j, (bx, by))
val area = (abs(ax - bx) + 1) * (abs(ay - by) + 1)
res := Cons((area, (min(ax, bx), min(ay, by)), (max(ax, bx), max(ay, by))), res)
()
res.sort()
pub fun part-one()
val coords = parse-input()
areas-sorted(coords).last.unjust.fst
fun intersects-any(lines: list<(int, (int, int))>, from: int, to: int)
lines.any(fn ((_, (start, end))) to > start && from < end)
pub fun part-two()
val coords = parse-input()
val candidates = areas-sorted(coords).reverse()
val pairs = coords.pairwise()
/// Optimization potential: sort the lines for faster pruning of relevant ones
val horizontal-lines = pairs
.filter(fn (((_, ay), (_, by))) ay == by)
.map(fn (((ax , ay), (bx, _))) if ax < bx then (ay, (ax, bx)) else (ay, (bx, ax)))
val vertical-lines = pairs
.filter(fn (((ax, _), (bx, _))) ax == bx)
.map(fn (((ax , ay), (_, by))) if ay < by then (ax, (ay, by)) else (ax, (by, ay)))
with outer <- early-exit
candidates.foreach fn ((area, (ulx, uly), (lrx, lry)))
val check-verticals = vertical-lines.filter(fn ((x, _)) x > ulx && x < lrx)
if intersects-any(check-verticals, uly, lry) then
return ()
val check-horizontals = horizontal-lines.filter(fn ((y, _)) y > uly && y < lry)
if intersects-any(check-horizontals, ulx, lrx) then
return ()
/// Technically, we would also have to check if the box lies fully outside of the shape.
/// Luckily, the input is formatted in a way that we encounter the correct solution before running into such a case.
/// I still need to buy some christmas presents, so let's call it a day.
outer.exit(area)
0
pub fun main()
with day(9)
// with example-input
// part-one()
part-two()