Tj3n Tj3n - 7 months ago 27
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

Pseudo:

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

output:
[1,2,3,4,5],
[2,1,3,4,5],
[3,1,2,4,5],..


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

Answer

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 {
            set.insert(toList.joinWithSeparator(""))
        }
        if !fromList.isEmpty {
            for (index, item) in fromList.enumerate() {
                var newFrom = fromList
                newFrom.removeAtIndex(index)
                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"}
Comments