|
| 1 | +fun String.parseLists(): Any { |
| 2 | + val stack: MutableList<MutableList<Any>> = mutableListOf(mutableListOf()) |
| 3 | + this.replace("]", ",}").replace("[", "{,").replace(",,", ",").split(",").forEach { |
| 4 | + when (it) { |
| 5 | + "{" -> { val m: MutableList<Any> = mutableListOf(); stack.last().add(m); stack.add(m) } |
| 6 | + "}" -> stack.removeLast() |
| 7 | + else -> stack.last().add(it.toInt()) |
| 8 | + } |
| 9 | + } |
| 10 | + return stack[0][0] |
| 11 | +} |
| 12 | + |
| 13 | +fun cmp(a: Any, b: Any): Int { |
| 14 | + if (a is Int && b is Int) |
| 15 | + return when { a < b -> -1; a > b -> 1; else -> 0 } |
| 16 | + val aList = if (a is MutableList<*>) a else mutableListOf(a) |
| 17 | + val bList = if (b is MutableList<*>) b else mutableListOf(b) |
| 18 | + for ((u, v) in aList zip bList) |
| 19 | + if (cmp(u!!, v!!) != 0) |
| 20 | + return cmp(u, v) |
| 21 | + return cmp(aList.size, bList.size) |
| 22 | +} |
| 23 | + |
| 24 | +fun main() { |
| 25 | + var lists = generateSequence(::readlnOrNull) |
| 26 | + .filter { !it.isEmpty() } |
| 27 | + .map { it.parseLists() } |
| 28 | + .toMutableList() |
| 29 | + |
| 30 | + lists |
| 31 | + .chunked(2) |
| 32 | + .withIndex() |
| 33 | + .filter { (_, pair) -> cmp(pair[0], pair[1]) <= 0 } |
| 34 | + .sumOf { (i, _) -> i+1 } |
| 35 | + .also(::println) |
| 36 | + |
| 37 | + val distress = listOf(listOf(listOf(2)), listOf(listOf(6))) |
| 38 | + lists |
| 39 | + .also { it.addAll(distress) } |
| 40 | + .sortedWith(::cmp) |
| 41 | + .withIndex() |
| 42 | + .filter { it.value in distress } |
| 43 | + .fold(1) { acc, (i, _) -> (i+1) * acc } |
| 44 | + .also(::println) |
| 45 | +} |
0 commit comments