jules0707

Game2048Helper.kt

Nov 18th, 2021 (edited)
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.94 KB | None | 0 0
  1. package games.game2048
  2.  
  3. /*
  4.  * This function moves all the non-null elements to the beginning of the list
  5.  * (by removing nulls) and merges equal elements.
  6.  * The parameter 'merge' specifies the way how to merge equal elements:
  7.  * it returns a new element that should be present in the resulting list
  8.  * instead of two merged elements.
  9.  *
  10.  * If the function 'merge("a")' returns "aa",
  11.  * then the function 'moveAndMergeEqual' transforms the input in the following way:
  12.  *   a, a, b -> aa, b
  13.  *   a, null -> a
  14.  *   b, null, a, a -> b, aa
  15.  *   a, a, null, a -> aa, a
  16.  *   a, null, a, a -> aa, a
  17.  *
  18.  * You can find more examples in 'TestGame2048Helper'.
  19. */
  20. fun <T : Any> List<T?>.moveAndMergeEqual(merge: (T) -> T): List<T> {
  21.  
  22.     return this.filterNotNull().fold(listOf()) { acc, e ->
  23.         if (acc.isEmpty() || acc.last() != e) {
  24.             acc.plus(e)
  25.         } else {
  26.             acc.dropLast(1).plus(merge(e))
  27.         }
  28.     }
  29. }
  30.  
Add Comment
Please, Sign In to add comment