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)ephemient
01/23/2023, 8:17 PMremoveLast() 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 protectedCLOVIS
01/23/2023, 8:19 PMLukasz Kalnik
01/23/2023, 8:19 PMephemient
01/23/2023, 8:19 PMjava.util.AbstractList, not kotlin.collections.MutableListLukasz Kalnik
01/23/2023, 8:23 PMrepeat(n) { list.removeLast() } was fasterLukasz Kalnik
01/23/2023, 8:28 PMLukasz Kalnik
01/23/2023, 8:29 PMprivate 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)
}
}Lukasz Kalnik
01/23/2023, 8:29 PMprivate 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)
}
}Lukasz Kalnik
01/23/2023, 8:30 PMLukasz Kalnik
01/23/2023, 8:32 PMsourceStack and destinationStack are ArrayDeque<Char>Lukasz Kalnik
01/23/2023, 8:33 PMAbstractMutableListLukasz Kalnik
01/23/2023, 8:35 PMrepeat { 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 PMLukasz Kalnik
01/23/2023, 8:51 PM