Created
December 17, 2019 16:11
-
-
Save Tolsi/686dbbe267b04d92874891d744545f87 to your computer and use it in GitHub Desktop.
Kotlin List permutations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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