我使用的枚举和switch语句,企图字母组合映射到数字的字符串给予。这类似于电话词算法,其中给你一个电话号码,必须找到该号码映射可能的话。在这里,我并不想找到实际的英语单词,一定是。而是相反,信件只是基本String
。
下面的代码是不是在操场出于某种原因打印。
enum Dialpad : Int {
case zero, one, two, three, four
var letters : [String] {
switch self {
case .zero,.one:
return []
case .two:
return ["a","b","c"]
case .three:
return ["d","e","f"]
case .four:
return ["g","h","i"]
}
}
}
这里是结合Character
阵列到阵列String
递归函数。
func comboArray(_ arrays:[[String]], n:Int,set:inout Set<String>) {
if n >= arrays.count { return }
let array = arrays[n]
if set.isEmpty {
set = Set(array)
} else {
set.forEach { (c1) in
array.forEach({ (c2) in
set.insert(c1+c2)
})
if !array.isEmpty {
set.remove(c1)
}
}
}
comboArray(arrays, n: n+1, set: &set)
}
这个功能应该在一些并将其映射到相应的拨号盘字母。
func dialPadLetters(number:Int) -> Set<String> {
let stringNumber = String(number)
var arrayLetter : [Array<String>] = []
for c in stringNumber {
let n = Int(String(c))!
let letters = Dialpad(rawValue: n)!.letters
arrayLetter.append(letters)
}
var mySet : Set<String> = []
comboArray(arrayLetter, n: 0, set: &mySet)
return mySet
}
然后,我尝试打印的字母a,b,C,d,E,F,G,H的可能的组合,我因为给定的拨号盘号码是0,1,2,3,4。(注意,0和1不包含拨号盘字母。)
let theSet = dialPadLetters(number: 1234)
print("\(theSet)")
看来你的游乐场坏了,因为你的代码对我的作品和版画["adh", "bdg", "afi", "bdi", "beh", "bdh", "bfg", "adg", "bfi", "aeh", "cdi", "aeg", "bfh", "cfi", "afg", "cfg", "aei", "afh", "bei", "ceg", "cdh", "cei", "adi", "cdg", "ceh", "cfh", "beg"]