data class Coordinate3D(val x:Int, val y:Int, val z:Int) : Comparable { override fun compareTo(other: Coordinate3D) = (abs(x) + abs(y) + abs(z)).compareTo(abs(other.x) + abs(other.y)+abs(other.z)) operator infix fun plus(other: Coordinate3D) = Coordinate3D(this.x + other.x, this.y + other.y, this.z + other.z) } typealias Acceleration = Coordinate3D typealias Velocity = Coordinate3D typealias Position = Coordinate3D class SwarmItem(val pos: Position, val velocity: Velocity, val acceleration: Acceleration) : Comparable{ override fun compareTo(other: SwarmItem): Int = compareValuesBy(this, other, { it.acceleration }, { it.velocity }, { it.pos}) constructor(x:Int,y:Int,z:Int, vx:Int,vy:Int,vz:Int, ax:Int,ay:Int,az:Int) : this(Position(x,y,z), Velocity(vx,vy,vz), Acceleration(ax,ay,az)) fun move() : SwarmItem { val newV = velocity + acceleration val newPos = pos + newV return SwarmItem( newPos, newV, this.acceleration) } } fun List.removeCollisions() : List{ return this.groupBy { it.pos }.filter { it.value.size == 1 }.flatMap { it.value } } fun part2(items: List): List{ return (0..1000).fold(items){ prev, _ -> prev.map { it.move() }.removeCollisions() } } fun main(args: Array) { val items = input.split("\n").map { Regex(ENTRY_REGEX).matchEntire(it) } .filterNotNull().map{ it.groupValues.drop(1).map(String::toInt) } .map { SwarmItem(it[0],it[1],it[2],it[3],it[4],it[5],it[6],it[7],it[8]) } println("Part 1: " + items.withIndex().minBy { it.value }?.index) println("Part 2: " + part2(items).size) } const val N = "(-?\\d*)" const val ENTRY_REGEX = "^p=<$N,$N,$N>, v=<$N,$N,$N>, a=<$N,$N,$N>"