Files
kotlin-for-java-developers/src/assignment/week5/games/game2048/Game2048Helper.kt

42 lines
1.1 KiB
Kotlin
Raw Normal View History

2025-07-31 12:09:49 +02:00
package games.game2048
/*
* This function moves all the non-null elements to the beginning of the list
* (by removing nulls) and merges equal elements.
* The parameter 'merge' specifies the way how to merge equal elements:
* it returns a new element that should be present in the resulting list
* instead of two merged elements.
*
* If the function 'merge("a")' returns "aa",
* then the function 'moveAndMergeEqual' transforms the input in the following way:
* a, a, b -> aa, b
* a, null -> a
* b, null, a, a -> b, aa
* a, a, null, a -> aa, a
* a, null, a, a -> aa, a
*
* You can find more examples in 'TestGame2048Helper'.
*/
fun <T : Any> List<T?>.moveAndMergeEqual(merge: (T) -> T): List<T> {
val mutableList = mutableListOf<T>()
val oldList = filterNotNull()
var index = 0
while (true) {
if (index >= oldList.size) break
val first = oldList[index]
val second = oldList.getOrNull(index + 1)
if (first == second) {
index += 2
mutableList.add(merge(first))
} else {
index += 1
mutableList.add(first)
}
}
return mutableList
}