Skip to content

Commit

Permalink
2024 - Day 09 - part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
fmmr committed Dec 9, 2024
1 parent 80aa559 commit e0219c6
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 11 deletions.
46 changes: 37 additions & 9 deletions src/main/kotlin/no/rodland/advent_2024/Day09.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,55 @@ import no.rodland.advent.Day
// template generated: 09/12/2024
// Fredrik Rødland 2024

class Day09(val input: List<String>) : Day<Long, Long, Pair<List<Int>, List<Int>>> {
class Day09(val input: List<String>) : Day<Long, Long, Pair<Int, List<Day09.Num?>>> {

private val parsed = input.parse()
private val files = parsed.first
private val space = parsed.second
val size = parsed.first
val parsedList = parsed.second

override fun partOne(): Long {
parsed
return 2
val list = parsedList.toMutableList()
val memory = (0..<size).map { idx ->
list[idx] ?: list.removeLastNonNull()
}
return memory.map { it.id }.checksum()
}

private fun MutableList<Num?>.removeLastNonNull(): Num {
var last = removeLast()
while (last == null) {
last = removeLast()
}
return last
}

private fun Iterable<Int>.checksum(): Long = foldIndexed(0L) { i, acc, id -> acc + i * id }

override fun partTwo(): Long {
return 2
}

override fun List<String>.parse(): Pair<List<Int>, List<Int>> {
return first()
override fun List<String>.parse(): Pair<Int, List<Num?>> {
var id = 0
var size = 0
val chunked = first()
.map { c -> c.digitToInt() }
.chunked(2) { it.first() to it.last() }
.unzip()
.chunked(2) {
val num = Num(id++, it.first())
size += it.first()
if (it.size == 2) {
num to it.last()
} else {
num to null
}
}
val flatMap = chunked.flatMap { (num, space) ->
(0..<num.size).map { num } + (space?.let { (0..<space).map { null } } ?: emptyList())
}
return size to flatMap
}

data class Num(val id: Int, val size: Int)

override val day = "09".toInt()
}
5 changes: 3 additions & 2 deletions src/test/kotlin/no/rodland/advent_2024/Day09Test.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ internal class Day09Test {
private val data09 = "2024/input_09.txt".readFile()
private val test09 = "2024/input_09_test.txt".readFile()

private val resultTestOne = 2L
private val resultTestOne = 1928L
private val resultTestTwo = 2L
private val resultOne = 2L
private val resultOne = 6421128769094L
private val resultTwo = 2L

val test = defaultTestSuiteParseOnInit(
Expand All @@ -29,6 +29,7 @@ internal class Day09Test {
resultTwo,
{ Day09(data09) },
{ Day09(test09) },
numTestPart1 = 200
)

@Nested
Expand Down

0 comments on commit e0219c6

Please sign in to comment.