Created
April 26, 2019 12:26
-
-
Save drosenstark/7454d39aa42b8ab132781e720cd80374 to your computer and use it in GitHub Desktop.
String permutations in a way that makes some sense
This file contains 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
import Foundation | |
func permute(_ s: String) -> [String] { | |
var arr = Array(s) | |
var permutations = [[Character]]() | |
permute(&arr, 0, &permutations) | |
return permutations.map { String($0) } | |
} | |
func permute<T>(_ arr: inout [T], _ k: Int, _ result: inout [[T]]) { | |
for i in k ..< arr.count { | |
arr.swapAt(i, k) | |
permute(&arr, k + 1, &result) | |
arr.swapAt(k, i) | |
} | |
if k == arr.count - 1 { result.append(arr) } | |
} | |
print(permute("whoah")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment