Added obligatory assignments

This commit is contained in:
Martin Berg Alstad
2025-07-31 12:09:49 +02:00
committed by Martin Berg Alstad
parent 64d9e4ada7
commit 92c416ab8b
17 changed files with 815 additions and 0 deletions

View File

@ -0,0 +1,41 @@
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
}