swift - 一组具有可选字符串属性的对象,改进接受字符串参数的函数并在集合中找到最佳匹配

标签 swift algorithm pattern-matching string-matching

我们正在尝试优化我们一直在使用的一些“加权”匹配算法,并决定查阅互联网以获取更多想法

我们有一个结构 MyStruct ,具有 5 个可选属性(在 swift 中,这仅意味着该属性可以是 nil ):

prop1: String?
prop2: String?
prop3: String?
prop4: String?
prop5: String?

然后我们有一组MyStruct (保证没有 2 个实例具有完全相同的属性),

structArray: Set<MyStruct>

我们有一个函数,它接受这个数组以及字典中的 1-5 个属性,以返回 1 个最匹配的单个实例。如果任何属性不匹配,实例将立即退出竞争

func findBestMatch(forSet set:Set<MyStruct>, andArgs argDict:[String:String]) -> MyStruct? {
  //Will use this to store any matches, as well as an associated match score
  var bestMatch: MyStruct?
  var topScore = 0
  for element in set {
    var score = 0
    if let p1 = argDict["p1"] {
      if p1 == element.prop1 {
        score += 16 //p1 match has highest weight
      } else {
        continue
      }
    }

    if let p2 = argDict["p2"] {
      if p2 == element.prop2 {
        score += 8 //p2 match has second-highest weight
      } else {
        continue
      }
    }

    //etc for the other 3 properties

    if score > topScore {
      topScore = score
      bestMatch = element 
    }
  }
  return bestMatch
}

示例:

exInstance1
  prop1 = "no good"
  prop2 = nil
  prop3 = "goodbye

exInstance2
  prop1 = "hello"
  prop2 = "noproblem"
  prop3 = "goodbye"

exInstance3
  prop1 = nil
  prop2 = nil
  prop3 = "goodbye"

exampleSet: Set<MyStruct> = [exInstance1, exInstance2, exInstance3]

matchingProperties: [String:String] = {
  "p1": "hello",
  "p3": "goodbye"
}


findBestMatch(forSet: exampleSet, andArgs: matchingProperties)

exInstance1 在 prop3 上只有 1 个匹配,但是因为 prop1 根本不匹配,所以没有给 exInstance 打分

exInstance2 在两个属性上都匹配,得分为 20

exInstance3 匹配一个属性,得分为 4

exInstance2 被选中并返回


问题:有更好的方法吗?如果没有,我们有什么方法可以改进这个算法吗?

最佳答案

如果您将字典访问排除在 for 循环之外,我只会看到轻微的改进,例如

func findBestMatch(forSet set:Set<MyStruct>, andArgs argDict:[String:String]) -> MyStruct? {
    //Will use this to store any matches, as well as an associated match score
    var bestMatch: MyStruct?
    var topScore = 0
    let p1 = argDict["p1"]
    let p2 = argDict["p2"]  // and so on
    for element in set {
        var score = 0
        if let p1 = p1 {
            if p1 == element.prop1 {
                score += 16 //p1 match has highest weight
            } else {
                continue
            }
        }

        //etc for the other properties

        if score > topScore {
            topScore = score
            bestMatch = element
        }
    }
    return bestMatch
}

关于swift - 一组具有可选字符串属性的对象,改进接受字符串参数的函数并在集合中找到最佳匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54872752/

相关文章:

ios - 如何使用 PHCachingImageManager

arrays - 基于另一个数组快速排序数组

java - Dekker 的算法不适用于三个进程

scala - 如何在 Scala 中抑制 "match is not exhaustive!"警告

haskell - 如何处理非详尽模式匹配的误报?

swift - tvOS:UIButton 的 UIMotionEffect 滑动时不会反弹

ruby - 我可以使用 Swift 的 Ruby 正则表达式引擎吗?

Java灯泡开关问题

python - 实现具有最大深度并打印所有最短路径的 BFS 算法

sql - B树索引好像没有用?