Skip to content

Instantly share code, notes, and snippets.

@abey
Created March 29, 2020 22:12
Show Gist options
  • Save abey/8f13eecfe9f580837f00a849a0e6f234 to your computer and use it in GitHub Desktop.
Save abey/8f13eecfe9f580837f00a849a0e6f234 to your computer and use it in GitHub Desktop.
Generate Permutations of a Swift Array
// abey.dev
import Foundation
extension Array {
func decompose() -> (Iterator.Element, [Iterator.Element])? {
guard let x = first else { return nil }
return (x, Array(self[1..<count]))
}
}
func between<T>(x: T, _ ys: [T]) -> [[T]] {
guard let (head, tail) = ys.decompose() else { return [[x]] }
return [[x] + ys] + between(x: x, tail).map { [head] + $0 }
}
func permutations<T>(for items: [T]) -> [[T]] {
guard let (head, tail) = items.decompose() else { return [[]] }
return permutations(for: tail).flatMap { between(x: head, $0) }
}
// Example
let permutations = permutations(for: [1, 2, 3])
// permutations = [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment