AdventOfCode-2017/day24.kt

68 lines
2.2 KiB
Kotlin

import java.io.File
typealias Piece = List<Int>
typealias Bridge = List<Piece>
fun Bridge.cost(): Int {
val lastcost = last().first()
val betweenCost = (0 until size - 1).map {
this[it].first() * 2
}.sum()
return betweenCost + lastcost
}
fun getPaths(bridge: Bridge, pieces: List<Piece>): List<Bridge> {
val compatiblePieces = pieces.filter { it.contains(bridge.last().first() ) }
if(compatiblePieces.size != 0) {
return compatiblePieces.map {
val newPiece = it.toMutableList()
newPiece.remove(bridge.last().first())
val newPieces = pieces.toMutableList()
newPieces.remove(it)
val newBridge = bridge.toMutableList()
newBridge.add(newPiece)
getPaths(newBridge, newPieces)
}.fold(mutableListOf()) {
a, b ->
val list = mutableListOf<Bridge>()
list.addAll(a)
list.addAll(b)
list
}
} else return mutableListOf(bridge)
}
fun main(args: Array<String>){
val file = File("../puzzle_24.txt")
// val file = File("test.txt")
val lines = file.readLines()
val firstLine = lines.first()
val transformedLines = lines.toMutableList().map {
val split = it.split("/")
mutableListOf(split[0].toInt(), split[1].toInt())
}
var index = 0
var initialCombinations = transformedLines
.filter { it.contains(0) }
.map {
val withoutZero = it.toMutableList()
withoutZero.remove(0)
val withoutZeroPiece = transformedLines.toMutableList()
withoutZeroPiece.remove(it)
mutableListOf(withoutZero) to withoutZeroPiece
}.toMutableList()
val paths = initialCombinations.map {
val (bridge, pieces) = it
getPaths(bridge, pieces)
}.fold(mutableListOf<Bridge>()) {
a, b ->
val list = mutableListOf<Bridge>()
list.addAll(a)
list.addAll(b)
list
}
println(paths.map { it.cost() }.max())
val maxLength = paths.map { it.size }.max()
val maxLenghtMaxStrength = paths.filter { it.size == maxLength }.maxBy { it.cost() }
println(maxLenghtMaxStrength!!.cost())
}