class Day24(input: List) { private val components = parseInput(input) fun solvePart1(): Int = makeBridges(components).maxBy { it.strength() }?.strength() ?: 0 fun solvePart2(): Int { return makeBridges(components) .groupBy { it.size } .maxBy { it.key }?.value?.maxBy { it.strength() }?.strength() ?: 0 } private fun makeBridges(components: List, port: Int = 0, bridge: List = emptyList()): List> { val pickList = components.filter { it.fitsWithPort(port) } return if (pickList.isEmpty()) { listOf(bridge) } else { pickList.flatMap { pick -> makeBridges( components.filterNot { it == pick }, pick.opposite(port), bridge + pick ) } } } private fun parseInput(input: List): List = input.map { it.split("/") }.map { BridgeComponent(it[0].toInt(), it[1].toInt()) } data class BridgeComponent(val x: Int, val y: Int) { val strength = x + y fun fitsWithPort(port: Int): Boolean = x == port || y == port fun opposite(port: Int): Int = x.takeUnless { x == port } ?: y } private fun List.strength(): Int = this.sumBy { it.strength } }