Skip to content

Instantly share code, notes, and snippets.

@jeroenr
Created March 6, 2023 15:57
Show Gist options
  • Select an option

  • Save jeroenr/b13a75e0cd7c890f8a147ab7d0447610 to your computer and use it in GitHub Desktop.

Select an option

Save jeroenr/b13a75e0cd7c890f8a147ab7d0447610 to your computer and use it in GitHub Desktop.

Revisions

  1. jeroenr created this gist Mar 6, 2023.
    8 changes: 8 additions & 0 deletions permutations.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    fun <T> List<T>.permutations(): List<List<T>> =
    when {
    size < 2 -> listOf(this)
    size == 2 -> listOf(listOf(first(), last()), listOf(last(), first()))
    else -> flatMap { element ->
    (this - element).permutations().map { listOf(element) + it }
    }
    }