Skip to content

Instantly share code, notes, and snippets.

@Tolsi
Created December 17, 2019 16:11
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 Tolsi/686dbbe267b04d92874891d744545f87 to your computer and use it in GitHub Desktop.
Save Tolsi/686dbbe267b04d92874891d744545f87 to your computer and use it in GitHub Desktop.
Kotlin List permutations
fun <T> List<T>.permutations(): Sequence<List<T>> {
if (this.size == 1) return sequenceOf(this)
val list = this
return sequence {
val sub = list.get(0)
for (perm in list.drop(1).permutations())
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, sub)
yield(newPerm)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment