Skip to content

Instantly share code, notes, and snippets.

@mkhl
Last active December 9, 2015 20:37
Show Gist options
  • Save mkhl/17c39107046a3d06945a to your computer and use it in GitHub Desktop.
Save mkhl/17c39107046a3d06945a to your computer and use it in GitHub Desktop.
Permutations of Sequences in Swift
func permutations<Sequence: SequenceType>(items: Sequence) -> [[Sequence.Generator.Element]] {
return items.reduce([[]]) { (perms, item) in
return perms.flatMap { perm in
return (0 ... perm.count).map { i in
var copy = perm
copy.insert(item, atIndex: i)
return copy
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment