Lukasz Kalnik
01/23/2023, 7:54 PMn
elements from a MutableList? I.e. equivalent of dropLast(Int)
for List
.
Something like MutableList.removeLast(Int)
CLOVIS
01/23/2023, 8:02 PMrepeat(4) { list.removeLast() }
?Sam
01/23/2023, 8:03 PMfun MutableList<*>.removeLast(n: Int) {
subList(size - n, size).clear()
}
CLOVIS
01/23/2023, 8:05 PMO(1)
removeLast
. Not sure how predictable subList(...).clear()
isephemient
01/23/2023, 8:16 PMjava.util.ArrayList
, subList(size - 1n, size).clear()
calls removeRange(size - n, size)
which is O(1)removeLast()
which is O(n)Lukasz Kalnik
01/23/2023, 8:17 PMCLOVIS
01/23/2023, 8:18 PMremoveRange(size-4, size)
. It's also the easiest to read.ephemient
01/23/2023, 8:19 PMremoveRange
because it is protected
CLOVIS
01/23/2023, 8:19 PMLukasz Kalnik
01/23/2023, 8:19 PMephemient
01/23/2023, 8:19 PMjava.util.AbstractList
, not kotlin.collections.MutableList
Lukasz Kalnik
01/23/2023, 8:23 PMrepeat(n) { list.removeLast() }
was fasterprivate fun executeMove(move: Move) {
with(move) {
val sourceStack = stacks[fromStack]
val destinationStack = stacks[toStack]
val crates = sourceStack.takeLast(numberOfCrates)
repeat(numberOfCrates) { sourceStack.removeLast() }
destinationStack.addAll(crates)
}
}
private fun executeMove(move: Move) {
with(move) {
val sourceStack = stacks[fromStack]
val destinationStack = stacks[toStack]
val crates = sourceStack.takeLast(numberOfCrates)
val sourceStackSize = sourceStack.size
sourceStack.subList(sourceStackSize - numberOfCrates, sourceStackSize).clear()
destinationStack.addAll(crates)
}
}
sourceStack
and destinationStack
are ArrayDeque<Char>
AbstractMutableList
repeat { removeLast() }
is a bit more readable than subList().clear()
ephemient
01/23/2023, 8:47 PMn
, repeat(n) { removeLast() }
(probably due to no temporary objects) while for large n
, subList().clear()
is fasterLukasz Kalnik
01/23/2023, 8:51 PM