I'm currently trying to make a Set
of all possible combinations from an Array
of Strings
, were each element contains only one letter.
The Array
itself can contain the same letter twice or even more and they should only be used as often as they occur.
The Set
should later contain all combinations from a minimum of 2 letters up to the length of the given Array
.
I searched here on stackoverflow, but only found permutation functions that ignore the fact, that each letter should only be used as often as they occur.
This is my first Swift 2 project, so please forgive my greenhornish-ness :)
What I want
var array = ["A", "B", "C","D"]
var combinations: Set<String>
... <MAGIC> ...
print(combinations)
// "AB", "ABC", "ABD", "ABCD", "ABDC", "AC", "ACB", "ACD", "ACBD", "ACDB", and so on ...
My current approach
func permuation(arr: Array<String>) {
for (index, elementA) in arr.enumerate() {
//1..2..3..4
var tmpString = elementA
var tmpArray = arr
tmpArray.removeAtIndex(index)
for (index2, elementB) in tmpArray.enumerate() {
// 12..13..14
var tmpString2 = tmpString + elementB
var tmpArray2 = tmpArray
//[3,4]
tmpArray2.removeAtIndex(index2)
results.append(tmpString2)
}
}
}
permuation(array)
print(results)
// "["AB", "AC", "AD", "BA", "BC", "BD", "CA", "CB", "CD", "DA", "DB", "DC"]"
I know, this is so terribly wrong in so many ways, but I'm stuck with this code, and don't know how to add a recursive functionality.