我有一本简单的字典var countOfR = ["R0": 0, "R1": 0, "R2": 0, "R3": 0, "R4": 0, "R5": 0, "R6": 0]
我需要根据多种条件检查这本词典。例如,next语句工作得很好:
for index in countOfR {
if index == ("R0",2) || index == ("R1",2) || index == ("R2",2) || index == ("R3",2) || index == ("R4",2) || index == ("R5",2) || index == ("R6",2) {
type = "P"
这会找到一对。但接下来我需要检查“两对”—“pp”。写这样的东西很可怕:
if index == ("R0",2) && index == ("R1",2) || index == ("R0",2) && index == ("R2",2) || index == ("R0",2) && index == ("R3",2) || index == ("R0",2) && index == ("R4",2) || index == ("R0",2) && index == ("R5",2) || index == ("R0",2) && index == ("R6",2) || ...
等等…我还需要搜索“对和三线”,“三对”和许多其他。
为了更好地理解:
["R0": 1, "R1": 2, "R2": 1, "R3": 1, "R4": 0, "R5": 1, "R6": 0]
是“p”,["R0": 1, "R1": 0, "R2": 0, "R3": 1, "R4": 0, "R5": 2, "R6": 0]
也是“p”,["R0": 1, "R1": 0, "R2": 2, "R3": 1, "R4": 0, "R5": 2, "R6": 0]
是“pp”我怎样才能解决这个任务?请给我一些建议!
最佳答案
你这样的东西是没有意义的,因为它永远不会true
。您的index
(或者它可能是什么名字)不能同时等于两个不同的东西。
我想您只需要计算值为2
的条目数。
你可以这样写:
func getType(_ countOfR: [String: Int]) -> String {
let pairs = countOfR.filter{$0.value == 2}.count
let trines = countOfR.filter{$0.value == 3}.count
let type = String(repeating: "P", count: pairs) + String(repeating: "T", count: trines)
return type
}
print(getType(["R0": 1, "R1": 2, "R2": 1, "R3": 1, "R4": 0, "R5": 1, "R6": 0]))
//->P
print(getType(["R0": 1, "R1": 0, "R2": 0, "R3": 1, "R4": 0, "R5": 2, "R6": 0]))
//->P
print(getType(["R0": 1, "R1": 0, "R2": 2, "R3": 1, "R4": 0, "R5": 2, "R6": 0]))
//->PP