Skip to content

Instantly share code, notes, and snippets.

@ryansobol
Last active August 12, 2021 15:38
Show Gist options
  • Save ryansobol/3301fc0025dba9294340b56d7d160297 to your computer and use it in GitHub Desktop.
Save ryansobol/3301fc0025dba9294340b56d7d160297 to your computer and use it in GitHub Desktop.
Generate the permutations of a Swift array
extension Array {
func chopped() -> (Element, [Element])? {
guard let x = self.first else { return nil }
return (x, Array(self.suffix(from: 1)))
}
}
print([1, 2, 3].chopped())
// Optional((1, [2, 3]))
extension Array {
func interleaved(_ element: Element) -> [[Element]] {
guard let (head, rest) = self.chopped() else { return [[element]] }
return [[element] + self] + rest.interleaved(element).map { [head] + $0 }
}
}
print([1, 2, 3].interleaved(0))
// [[0, 1, 2, 3], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]]
extension Array {
var permutations: [[Element]] {
guard let (head, rest) = self.chopped() else { return [[]] }
return rest.permutations.flatMap { $0.interleaved(head) }
}
}
print([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