Advertisement
Kostiggig

Untitled

Jun 3rd, 2023 (edited)
1,405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.86 KB | None | 0 0
  1. //Как мне из
  2. //listOf("a" to 2, "a" to 3)
  3. //Сделать
  4. //listOf("a" to 5)
  5.  
  6. fun main() {
  7.  
  8.     println(
  9.         solve(
  10.             listOf("a" to 2, "a" to 3) // -> [(a, 5)]
  11.         )
  12.     )
  13.  
  14.     println(
  15.         solve(
  16.             listOf("a" to 2, "a" to 3, "b" to 9, "c" to 0) // -> [(a, 5), (b, 9), (c, 0)]
  17.         )
  18.     )
  19.  
  20.     println(
  21.         solve(
  22.             listOf("a" to 2, "a" to 3, "b" to -1, "b" to 11, "c" to 0) // -> [(a, 5), (b, 10), (c, 0)]
  23.         )
  24.     )
  25. }
  26.  
  27. fun solve(list: List<Pair<String, Int>>): List<Pair<String, Int>> {
  28.     val result = mutableListOf<Pair<String, Int>>()
  29.     val map = mutableMapOf<String, Int>()
  30.  
  31.     list.forEach {(k, v) ->
  32.         map[k] = map.getOrDefault(k, 0) + v
  33.     }
  34.  
  35.     val keys = map.keys
  36.     keys.forEach {k ->
  37.         result.add(k to map[k]!!)
  38.     }
  39.  
  40.     return result
  41. }
  42.  
  43.  
  44.  
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement