Skip to content

Instantly share code, notes, and snippets.

@jeroenr
Created March 6, 2023 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeroenr/b13a75e0cd7c890f8a147ab7d0447610 to your computer and use it in GitHub Desktop.
Save jeroenr/b13a75e0cd7c890f8a147ab7d0447610 to your computer and use it in GitHub Desktop.
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 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment