0

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

Tj3n
  • 9,837
  • 2
  • 24
  • 35
  • Do you want to keep duplicates or not? – brimstone Apr 17 '16 at 05:01
  • Thanks for understanding, i have no idea also, logical code is basically can't have anything like "What have u tried?", just can or can't, i ask because i searched and couldn't find anything similar or easy enough even in other languages to convert x.x – Tj3n Apr 17 '16 at 05:01
  • I don't want to keep duplicates – Tj3n Apr 17 '16 at 05:01
  • 1
    You're looking for permutations. See this answer: http://stackoverflow.com/a/34969388/3810673 – Ian Apr 17 '16 at 05:13
  • Possible duplicate of [Calculate all permutations of a string in Swift](http://stackoverflow.com/questions/34968470/calculate-all-permutations-of-a-string-in-swift) – Hamish Apr 17 '16 at 06:54

2 Answers2

1

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"}
Community
  • 1
  • 1
brimstone
  • 3,370
  • 3
  • 28
  • 49
1

The code listed below is written basically on the back of the napkin, so while it might not be optimized in any way, it definitely produces the correct result. The basic idea is to iterate over the array and for each number:

  1. Create a new array, not containing current number.
  2. Generate all possible permutations for that new array (recursively)
  3. Prepend current number to every generated permutation.

Recursion terminates when the array for which to generate permutations contains only one element.

So having [1, 2, 3] as input: currentNumber == 1, subarray to generate permutations for is [2, 3]. Generating recursively all possible permutations for [2, 3] gives [2, 3] and [3, 2]. Prepending currentNumber (1) to both gives [1, 2, 3] and [1, 3, 2]. The same goes when currentNumber is equal to 2 and 3.

Code:

func allAvailablePermutationsForArray(array: [Int]) -> [[Int]]
{
    if (array.count == 1)
    {
        return [array]
    }

    var ret = [[Int]]()
    for number in array
    {
        var leftOver = array
        let index = leftOver.indexOf(number)
        leftOver.removeAtIndex(index!)
        let leftOverPermutations = allAvailablePermutationsForArray(leftOver)
        for var permutationsArray in leftOverPermutations
        {
            permutationsArray.insert(number, atIndex: 0)
            ret.append(permutationsArray)
        }
    }

    return ret
}

Running it the following way:

let array = [1, 2, 3, 4]
let res = allAvailablePermutationsForArray(array)

for (index, permuts) in res.enumerate()
{
    print("\(index + 1):\t\(permuts)")
}

the output is:

1:  [1, 2, 3, 4]
2:  [1, 2, 4, 3]
3:  [1, 3, 2, 4]
4:  [1, 3, 4, 2]
5:  [1, 4, 2, 3]
6:  [1, 4, 3, 2]
7:  [2, 1, 3, 4]
8:  [2, 1, 4, 3]
9:  [2, 3, 1, 4]
10: [2, 3, 4, 1]
11: [2, 4, 1, 3]
12: [2, 4, 3, 1]
13: [3, 1, 2, 4]
14: [3, 1, 4, 2]
15: [3, 2, 1, 4]
16: [3, 2, 4, 1]
17: [3, 4, 1, 2]
18: [3, 4, 2, 1]
19: [4, 1, 2, 3]
20: [4, 1, 3, 2]
21: [4, 2, 1, 3]
22: [4, 2, 3, 1]
23: [4, 3, 1, 2]
24: [4, 3, 2, 1]
Russian
  • 1,296
  • 10
  • 15