-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDay06.kt
49 lines (42 loc) · 1.59 KB
/
Day06.kt
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
/*
* Copyright (c) 2018 by Todd Ginsberg
*/
/**
* Advent of Code 2018, Day 6 - Chronal Coordinates
*
* Problem Description: http://adventofcode.com/2018/day/6
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day6/
*/
package com.ginsberg.advent2018
class Day06(input: List<String>) {
private val points: List<Point> = input.map { Point.of(it) }
private val xRange: IntRange = (points.minBy { it.x }!!.x..points.maxBy { it.x }!!.x)
private val yRange: IntRange = (points.minBy { it.y }!!.y..points.maxBy { it.y }!!.y)
fun solvePart1(): Int {
val infinite: MutableSet<Point> = mutableSetOf()
return xRange.asSequence().flatMap { x ->
yRange.asSequence().map { y ->
val closest = points.map { it to it.distanceTo(x, y) }.sortedBy { it.second }.take(2)
if (isEdge(x, y)) {
infinite.add(closest[0].first)
}
closest[0].first.takeUnless { closest[0].second == closest[1].second }
}
}
.filterNot { it in infinite }
.groupingBy { it }
.eachCount()
.maxBy { it.value }!!
.value
}
fun solvePart2(range: Int = 10_000): Int =
xRange.asSequence().flatMap { x ->
yRange.asSequence().map { y ->
points.map { it.distanceTo(x, y) }.sum()
}
}
.filter { it < range }
.count()
private fun isEdge(x: Int, y: Int): Boolean =
x == xRange.first || x == xRange.last || y == yRange.first || y == yRange.last
}