Tj3n Tj3n - 2 years ago 92
Swift Question

Create all possible array sort case

I'm having this piece of needing logical, but i totally seems lost about this, i need to create an array of all possible combination from a given single array


input: let array = [1,2,3,4,5]


Thanks a lot if someone can suggest the logic to do this

Answer Source

See this answer by vacawama for how this was made, and Martin R's answer to see performance comparisons. Code from answer:

func permute(list: [String], minStringLen: Int = 2) -> Set<String> {
    func permute(fromList: [String], toList: [String], minStringLen: Int, inout set: Set<String>) {
        if toList.count >= minStringLen {
        if !fromList.isEmpty {
            for (index, item) in fromList.enumerate() {
                var newFrom = fromList
                permute(newFrom, toList: toList + [item], minStringLen: minStringLen, set: &set)

    var set = Set<String>()
    permute(list, toList:[], minStringLen: minStringLen, set: &set)
    return set

permute(["A", "B", "C"])
// {"BA", "AC", "ABC", "AB", "BCA", "CB", "BC", "CAB", "ACB", "CA", "CBA", "BAC"}

permute(["A", "A", "B"])
// {"BA", "BAA", "AAB", "AB", "ABA", "AA"}

permute(["A", "A", "B"], minStringLen: 1)
// {"BA", "A", "BAA", "AB", "AA", "B", "AAB", "ABA"}

permute(["A", "A", "B"], minStringLen: 3)
// {"ABA", "BAA", "AAB"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download