iOS 11, Swift 4.0
Trying to write a recursive function to show all the possible combinations of a string. I got this, but its not quite right since I get only 20 pairs and I should get 24. I cannot see what I have missed here.
Where this coding going wrong?
var ans:Set<String>!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let str = "ABCD"
ans = []
recursiveString(s2s: str, char2s: 0)
print("\(ans) \(ans.count)")
}
func recursiveSwap(s2x: String, c2x: Int, j2m: Int) {
var anschr = Array(s2x)
let tmpchr = anschr[c2x]
anschr[c2x] = anschr[c2x+j2m]
anschr[c2x+j2m] = tmpchr
print("\(String(anschr))")
ans.insert(String(anschr))
if (c2x + j2m + 1) < s2x.count {
recursiveSwap(s2x: String(s2x), c2x: c2x, j2m: j2m+1)
} else {
if (c2x + 1) < s2x.count - 1 {
recursiveSwap(s2x: String(anschr), c2x: c2x + 1, j2m: 1)
}
}
}
func recursiveString(s2s: String, char2s: Int) {
let blue = shiftString(s2s: s2s)
if char2s < s2s.count {
recursiveSwap(s2x: blue, c2x: 0, j2m: 1)
recursiveString(s2s: blue, char2s: char2s + 1)
}
}
func shiftString(s2s: String) -> String {
let str2s = Array(s2s)
let newS = str2s.suffix(str2s.count - 1) + str2s.prefix(1)
return String(newS)
}
It give me ...
CBDA DCBA ACDB ADCB ABDC ABCD DCAB ADCB BDAC BADC BCAD BCDA ADBC BADC CABD CBAD CDBA CDAB BACD CBAD DBCA DCBA DACB DABC