Day 9 Part 2

This commit is contained in:
Sven Weidauer 2024-12-11 19:58:59 +01:00
parent 10b625d232
commit 1460448cff

View file

@ -8,6 +8,7 @@ sealed class Span {
fun main() { fun main() {
var currentFileId = 0 var currentFileId = 0
val input = readInputString("day9.txt").mapIndexed { index, c -> val input = readInputString("day9.txt").mapIndexed { index, c ->
if (index % 2 == 0) { if (index % 2 == 0) {
Span.File(currentFileId++, c.digitToInt()) Span.File(currentFileId++, c.digitToInt())
@ -17,6 +18,7 @@ fun main() {
} }
println("Part 1: ${part1(input)}") println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
} }
private fun part1(input: List<Span>): Long { private fun part1(input: List<Span>): Long {
@ -38,8 +40,42 @@ private fun part1(input: List<Span>): Long {
} }
} }
val checkSum = disk.calculateCheckSum() return disk.calculateCheckSum()
return checkSum }
private fun part2(input: List<Span>): Long {
val disk = input.toMutableList()
var index = disk.lastIndex
while (index > 0) {
val file = disk[index]
if (file !is Span.File) {
--index
continue
}
val target = disk.subList(0, index).indexOfFirst {
it is Span.Empty && it.length >= file.length
}
if (target != -1) {
disk[index] = Span.Empty(file.length)
val space = disk[target]
require(space is Span.Empty)
disk[target] = file
if (space.length > file.length) {
disk.add(target + 1, Span.Empty(space.length - file.length))
++index
}
}
--index
}
return disk.calculateCheckSum()
} }
private fun MutableList<Span>.takeFileBlocksFromEnd(blocks: Int): Span.File { private fun MutableList<Span>.takeFileBlocksFromEnd(blocks: Int): Span.File {
@ -62,12 +98,13 @@ private fun List<Span>.calculateCheckSum(): Long {
var currentBlock = 0L var currentBlock = 0L
for (file in this) { for (file in this) {
require(file is Span.File) when (file) {
is Span.Empty -> currentBlock += file.length
repeat(file.length) { is Span.File -> repeat(file.length) {
checkSum += currentBlock++ * file.id checkSum += currentBlock++ * file.id
} }
} }
}
return checkSum return checkSum
} }