Created
December 5, 2022 16:28
-
-
Save joaomneto/27aa3955863efff1a2314b9312715414 to your computer and use it in GitHub Desktop.
advent of code 2022 day 5 cparsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun parseFilePart1(inputStream: InputStream) = with(inputStream.bufferedReader()) { | |
var line: String? = null | |
val stacksRaw = mutableListOf<String>() | |
val moves = mutableListOf<List<Int>>() | |
var movesListBegun = false | |
while (true) { | |
line = readLine() | |
when { | |
line == null -> break | |
line.isBlank() -> movesListBegun = true | |
!movesListBegun -> stacksRaw.add(line) | |
else -> { | |
val values = MOVE_REGEX.find(line)!!.destructured.toList().map(String::toInt) | |
moves.add(values) | |
} | |
} | |
} | |
val numberStacks = stacksRaw.last().trim().split("""\s+""".toRegex()).last().toInt() | |
val stacks = (1..numberStacks).map { ArrayDeque<String>() } | |
stacksRaw.dropLast(1).reversed().forEach { line -> | |
(1..numberStacks).forEach { id -> | |
val crate = try { | |
(1 + 4 * (id - 1)).let { line.substring(it..it) } | |
} catch (e: StringIndexOutOfBoundsException) { | |
"" | |
} | |
if(crate.isNotBlank()) stacks[id - 1].add(crate) | |
} | |
} | |
stacks to moves | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment