Tj3n Tj3n - 6 months ago 10x
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


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"}