1
1
package day13
2
2
3
3
import java.io.File
4
- import kotlin.math.abs
5
4
6
5
val input = File (" src/main/kotlin/day13/Day13.txt" ).readLines().mapNotNull {
7
6
when (it) {
@@ -18,22 +17,54 @@ sealed class Data {
18
17
19
18
data class Compare (val first : Data , val second : Data )
20
19
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
23
30
}
24
31
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)
33
60
}
34
61
62
+ fun String.unwrapList () = removeSurrounding(" [" , " ]" )
35
63
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
+ )
37
68
}
38
69
39
70
sealed class Result {
0 commit comments