gistlib
Here's a simple recursive solution to get all permutations of a set in Swift:
main.swiftfunc permutations<T>(_ array: [T], _ length: Int? = nil, _ current: [T] = [], _ used: Set<Int> = .init()) -> [[T]] { let length = length ?? array.count if current.count == length { return [current] } else { var result: [[T]] = [] for (i, elem) in array.enumerated() where !used.contains(i) { var nextUsed = used nextUsed.insert(i) result += permutations(array, length, current + [elem], nextUsed) } return result } } 509 chars15 lines
func permutations<T>(_ array: [T], _ length: Int? = nil, _ current: [T] = [], _ used: Set<Int> = .init()) -> [[T]] { let length = length ?? array.count if current.count == length { return [current] } else { var result: [[T]] = [] for (i, elem) in array.enumerated() where !used.contains(i) { var nextUsed = used nextUsed.insert(i) result += permutations(array, length, current + [elem], nextUsed) } return result } }
You can use this function like this:
main.swiftlet set = [1, 2, 3] let perms = permutations(set) // returns [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] 128 chars3 lines
let set = [1, 2, 3] let perms = permutations(set) // returns [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
gistlibby LogSnag