Skip to content

Instantly share code, notes, and snippets.

@claytonjwong
Created November 20, 2021 17:09
Show Gist options
  • Save claytonjwong/418bb9a309cab9cae58e0aed1a051d95 to your computer and use it in GitHub Desktop.
Save claytonjwong/418bb9a309cab9cae58e0aed1a051d95 to your computer and use it in GitHub Desktop.
fun permutations(A: IntArray): Array<IntArray> {
var N = A.size
var perms = mutableListOf<IntArray>()
fun go(i: Int = 0) {
if (i == N) {
perms.add(A.copyOf())
return
}
for (k in i until N) {
A[i] = A[k].also{ A[k] = A[i] }
go(i + 1)
A[i] = A[k].also{ A[k] = A[i] }
}
}
go()
return perms.toTypedArray()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment