-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay20.kt
53 lines (42 loc) · 1.51 KB
/
Day20.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
50
51
52
53
package aoc2017.day20
import util.readInputLineByLine
import kotlin.math.abs
fun readInputToParticles(path: String): List<Particle> {
return readInputLineByLine(path)
.mapIndexed { index, string -> parseParticle(index, string) }
}
fun findClosestParticle(particles: List<Particle>): Int? {
return (1..1000).fold(particles) { acc, _ ->
acc.map { it.move() }
}.minByOrNull { it.position.distance }?.id
}
fun findClosestParticlePart2(particles: List<Particle>): Int {
return (1..1000).fold(particles) { acc, _ ->
acc.map { it.move() }
.groupBy { it.position }
.filterValues { it.size == 1 }
.flatMap { it.value }
}.size
}
private fun parseParticle(id: Int, inputString: String): Particle {
return inputString.split("<", ">").let {
Particle(id, parseVector(it[1]), parseVector(it[3]), parseVector(it[5]))
}
}
private fun parseVector(inputString: String): Vector {
return inputString
.split(",").map { it.trim().toLong() }
.let { Vector(it[0], it[1], it[2]) }
}
data class Vector(val x: Long, val y: Long, val z: Long) {
val distance = abs(x) + abs(y) + abs(z)
operator fun plus(other: Vector): Vector {
return Vector(x + other.x, y + other.y, z + other.z)
}
}
data class Particle(val id: Int, val position: Vector, val velocity: Vector, var acceleration: Vector) {
fun move() = this.copy(
velocity = velocity + acceleration,
position = position + velocity + acceleration
)
}