@@ -64,22 +64,24 @@ class Day09 @Inject constructor(
6464 emptySpace.length = (availableSpace - fileSize)
6565 memory.add(spaceIndex, Space .Full (fileSize, lastFile.file))
6666 spaceIndex++
67- memory.removeAt( lastFileIndex + 1 )
67+ memory[ lastFileIndex + 1 ] = Space . Empty (fileSize )
6868
6969 } else if (fileSize == availableSpace) {
7070 emptySpace.length = 0
7171 memory.add(spaceIndex, Space .Full (availableSpace, lastFile.file))
72- memory.removeAt(lastFileIndex -- + 1 )
73- memory.removeAt(spaceIndex + 1 )
72+ spaceIndex ++
73+ memory[lastFileIndex + 1 ] = Space . Empty (fileSize )
7474
7575 } else { // fileSize > availableSpace
7676 if (splitFiles) {
7777 emptySpace.length = 0
7878 memory.add(spaceIndex, Space .Full (availableSpace, lastFile.file))
79- memory.removeAt(spaceIndex + 1 )
8079
8180 lastFile.length - = availableSpace
81+ lastFileIndex++
8282
83+ spaceIndex++
84+ spaceIndex + = 2
8385 } else {
8486 var tempSpaceIndex = spaceIndex + 1
8587 var nextEmptySpace = (spaceIndex until lastFileIndex).firstOrNull { i ->
@@ -115,26 +117,21 @@ class Day09 @Inject constructor(
115117
116118 private fun checksum (memory : MutableList <Space >): Long {
117119 var index = 0L
118- return memory.asSequence()
119- .filter { space ->
120- when (space) {
121- is Space .Empty -> space.length > 0
122- is Space .Full -> space.length > 0
123- }
124- }
125- .sumOf { space ->
126- when (space) {
127- is Space .Empty -> { index + = space.length; 0 }
128- is Space .Full -> (1 .. space.length).sumOf { (index * space.file.id).also { index ++ } }
129- }
130- }
120+ return memory.sumOf { space ->
121+ when (space) {
122+ is Space .Empty -> 0
123+ is Space .Full -> (0 until space.length).sumOf { ((index + it) * space.file.id) }
124+ }.also { index + = space.length() }
125+ }
131126 }
132127
133128}
134129
135130data class File (val id : Int )
136131
137132sealed class Space {
138- data class Empty (var length : Int ) : Space()
139- data class Full (var length : Int , val file : File ) : Space()
133+ abstract fun length (): Int
134+
135+ data class Empty (var length : Int ) : Space() { override fun length () = length }
136+ data class Full (var length : Int , val file : File ) : Space() { override fun length () = length }
140137}
0 commit comments