我想将Set<Int>作为参数传递给函数。当我这么做时:
let setsOfWinningCells: Set = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ]
func isWinner(playerCells: Set<Int>) {
for winningCells in setsOfWinningCells {
if playerCells.isSupersetOf(winningCells) {
// do something
}
}
}编译器抱怨它是cannot invoke 'isSuperSetOf' with an argument list of type '(NSArray)'。使用Set<Int>()而不是Set<Int>也不起作用。
有人知道正确的语法吗?谢谢
澄清
我错误地认为问题是将集合正确地传递给函数,但实际上问题不是正确地定义集合集。为困惑而道歉。
发布于 2016-07-20 13:32:07
谢谢你,哈米什,你指出了我错过了什么。我的问题不是不正确地传递集合,而是我的Set of Set<Int>没有正确定义。我最初的定义是指它是Set of Arrays of Int。它应该是:
let setsOfWinningCells: Set<Set<Int>> = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ]发布于 2016-07-20 09:47:22
winningCells是NSArray,您应该为isSupersetOf(_)函数传递一组
发布于 2016-07-20 12:24:45
让我们试着更好地定义你的问题。
集团结构
让我们定义一个结构来表示一组Int(s)的概念。我们还希望结构是Hashable。
struct Group: Hashable {
let values: Set<Int>
var hashValue: Int { return values.hashValue }
}
func ==(left:Group, right:Group) -> Bool {
return left.values == right.values
}获胜组
现在让我们创建一个获胜组的列表。
let winningGroups: Set<Group> = [
Group(values:[0,1,2]),
Group(values:[3,4,5]),
Group(values:[6,7,8]),
Group(values:[0,3,6]),
Group(values:[1,4,7]),
Group(values:[2,5,8]),
Group(values:[0,4,8]),
Group(values:[2,4,6])
]玩家组
接下来我们有一个玩家组的列表。
let playerGroups: Set<Group> = [
Group(values:[4,0,8]),
Group(values:[2,4,6])
]找到选手的获胜组(准确匹配)
现在我们要选择playerGroups和winningGroups中的所有组。
let playerWinningGroups = playerGroups.intersect(winningGroups)
//[Group(values: Set([5, 4, 3])), Group(values: Set([2, 0, 1]))]正如您可以确定的,组内
Int(s)的顺序是,而不是相关的。 例如,玩家有[4,3,5],获胜的组是[3,4,5]。即使值按不同的顺序排列,也仍然会将组添加到结果中。
寻找获胜组(超级组)
让我们考虑一下这个玩家组
let playerGroups: Set<Group> = [
Group(values:[4,0,8]),
Group(values:[2,4,6]),
Group(values:[6,7,8,9]),
]第三组是获胜小组[6,7,8,9]的超集。但是,前面的解决方案没有选择这个元素。
让我们看看一个同样返回winningGroups的超级组的解决方案
var res = Set<Group>()
playerGroups.forEach { (playerGroup) in
if (winningGroups.contains({ (winninGroup) -> Bool in return winninGroup.values.isSubsetOf(playerGroup.values) })) {
res.insert(playerGroup)
}
}
print(res) // [Group(values: Set([2, 4, 6])), Group(values: Set([6, 7, 9, 8])), Group(values: Set([4, 0, 8]))]https://stackoverflow.com/questions/38477437
复制相似问题