Skip to content

Commit 754d4df

Browse files
committed
Add day 13
1 parent 047ac79 commit 754d4df

File tree

3 files changed

+46
-1
lines changed

3 files changed

+46
-1
lines changed

2022/13/13.kt

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

Media/2022/13.png

-168 Bytes
Loading

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
<a href="2022/12/12.kt">
4343
<img src="Media/2022/12.png" width="161px">
4444
</a>
45-
<a href="2022/13/13.py">
45+
<a href="2022/13/13.kt">
4646
<img src="Media/2022/13.png" width="161px">
4747
</a>
4848
<h1 align="center">

0 commit comments

Comments
 (0)