Added obligatory assignments
This commit is contained in:
41
src/assignment/week5/games/game2048/Game2048Helper.kt
Normal file
41
src/assignment/week5/games/game2048/Game2048Helper.kt
Normal 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
|
||||
}
|
||||
|
Reference in New Issue
Block a user