Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. /**
  2. * Returns permutation of elements of the receiver.
  3. *
  4. * ```
  5. * listOf("A", "B", "C").permutation(2) // -> [[A, B], [A, C], [B, A], [B, C], [C, A], [C, B]]
  6. * ```
  7. *
  8. * @param count number of elements of permutation.
  9. */
  10. fun <T> Iterable<T>.permutation(count: Int): List<List<T>> {
  11. require(count >= 0)
  12.  
  13. val inputList = if (this is List<T>) this else toList()
  14. require(count <= inputList.size)
  15.  
  16. return inputList.subPermutation(count)
  17. }
  18.  
  19. private fun <T> List<T>.subPermutation(count: Int): List<List<T>> {
  20. if (count == 1) return map { listOf(it) }
  21.  
  22. return (0 until size).flatMap { index ->
  23. val first = listOf(this[index])
  24. (subList(0, index) + subList(index + 1, size))
  25. .subPermutation(count - 1)
  26. .map { first + it }
  27. }
  28. }
  29.  
  30. /**
  31. * Returns combination of elements of the receiver.
  32. *
  33. * ```
  34. * listOf("A", "B", "C", "D").combination(3) // -> [[A, B, C], [A, B, D], [A, C, D], [B, C, D]]
  35. * ```
  36. *
  37. * @param count number of elements of combination.
  38. */
  39. fun <T> Iterable<T>.combination(count: Int): List<List<T>> {
  40. require(count >= 0)
  41.  
  42. val inputList = if (this is List<T>) this else toList()
  43. require(count <= inputList.size)
  44.  
  45. return inputList.subCombination(count)
  46. }
  47.  
  48. private fun <T> List<T>.subCombination(count: Int): List<List<T>> {
  49. if (count == 1) return map { listOf(it) }
  50.  
  51. return (0 until size - (count - 1)).flatMap { index ->
  52. val first = listOf(this[index])
  53. subList(index + 1, size)
  54. .subCombination(count - 1)
  55. .map { first + it }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement