Skip to content

Commit ebdcad0

Browse files
committed
day 13 checkpoint
1 parent 8e08408 commit ebdcad0

File tree

1 file changed

+43
-12
lines changed

1 file changed

+43
-12
lines changed

src/main/kotlin/day13/Day13.kt

Lines changed: 43 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package day13
22

33
import java.io.File
4-
import kotlin.math.abs
54

65
val input = File("src/main/kotlin/day13/Day13.txt").readLines().mapNotNull {
76
when (it) {
@@ -18,22 +17,54 @@ sealed class Data {
1817

1918
data class Compare(val first: Data, val second: Data)
2019

21-
fun String.parseList() = this.split(",", limit = 2).fold(listOf()) { acc: List<Data>, s: String ->
22-
acc + s.parseElement()
20+
fun String.findClosingBracketFromPos(openBracketPos: Int): Int {
21+
var closedBracketPos = openBracketPos
22+
var counter = 1
23+
while (counter > 0) {
24+
when (this[++closedBracketPos]) {
25+
']' -> counter--
26+
'[' -> counter++
27+
}
28+
}
29+
return closedBracketPos
2330
}
2431

25-
fun String.parseElement(): Data = when {
26-
this.toIntOrNull() != null -> Data.Integer(this.toInt())
27-
this == "" -> Data.ListData(listOf())
28-
else -> Data.ListData(
29-
this.substringAfter("[")
30-
.substringBefore("]")
31-
.parseList()
32-
)
32+
fun String.parseLine(): Data {
33+
if (isEmpty()) return Data.ListData(listOf())
34+
35+
val list = mutableListOf<Data>()
36+
37+
var index = 0
38+
while (index < count()) {
39+
when (val char = this[index]) {
40+
'[' -> {
41+
val closedPos = this.findClosingBracketFromPos(index)
42+
val sub = substring(startIndex = index + 1, endIndex = closedPos)
43+
list.add(sub.parseLine())
44+
index = closedPos + 1
45+
}
46+
47+
',' -> {
48+
index++
49+
}
50+
51+
else -> {
52+
list.add(Data.Integer(char.digitToInt()))
53+
index++
54+
}
55+
}
56+
57+
}
58+
59+
return Data.ListData(list)
3360
}
3461

62+
fun String.unwrapList() = removeSurrounding("[", "]")
3563
fun parseInput(input: () -> List<String>): List<Compare> = input().chunked(2).map {
36-
Compare(it.component1().parseElement(), it.component2().parseElement())
64+
Compare(
65+
it.component1().unwrapList().parseLine(),
66+
it.component2().unwrapList().parseLine()
67+
)
3768
}
3869

3970
sealed class Result {

0 commit comments

Comments
 (0)