Skip to content

Instantly share code, notes, and snippets.

@joaomneto
Created December 5, 2022 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaomneto/27aa3955863efff1a2314b9312715414 to your computer and use it in GitHub Desktop.
Save joaomneto/27aa3955863efff1a2314b9312715414 to your computer and use it in GitHub Desktop.
advent of code 2022 day 5 cparsing
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