Reputation: 109
Hi guys I want to ask how do you search the items for the nearest possible similar value regarding of the sequence. Example as below when I search for ["Restaurant","Bull"], it should return me str2 is the possible nearest values. Because this function only able to work for order sequence, it cannot for non-sequence. I really hope you guys can help me out....
func search(`for` searchItems: Set<String>, `in` searchArea: [Set<String>]) -> Set<String>? {
return searchArea.max(by: { (a, b) -> Bool in
return searchItems.intersection(a).count < searchItems.intersection(b).count || searchItems.intersection(a).count > searchItems.intersection(b).count
})
}
let str2: Set<String> = ["Bull","Restaurant","Corner"]
let str3: Set<String> = ["Corner","Restaurant","Mole"]
let area = [str3, str2] as [Any]
print("search result",self.search(for: ["Restaurant","Bull"], in: area as! [Set<String>]))
Upvotes: 0
Views: 106
Reputation: 9943
Probably because your str2
and str3
is not Set
at all, it's array coz you are using array declaration, thus change it to this then it works if you use ["Bull", "Restaurant"]
:
let str2 = Set(["Bull","Restaurant","Corner"])
let str3 = Set(["Corner","Restaurant","Mole"])
Also, Set
is non-ordered sequence, Array
is ordered sequence
Upvotes: 1
Reputation: 986
Just make a set out of your query array and use its isSubset(of:)
method to check wether it's a subset of your data.
let set1 = Set([1,2,3])
let set2 = Set([2,3,4])
let query = [1,2]
let querySet = Set(query)
querySet.isSubset(of: set1) // true
querySet.isSubset(of: set2) // false
let query2 = [2,1]
let querySet2 = Set(query)
querySet2.isSubset(of: set1) // true
querySet2.isSubset(of: set2) // false
Upvotes: 0