【问题标题】:Algorithm for finding record with most matching attributes查找具有最匹配属性的记录的算法
【发布时间】:2011-01-12 12:25:36
【问题描述】:
我正在寻找某种算法,该算法针对具有 n 个属性的给定记录,每个属性具有 n 个可能值(int、string 等),搜索多个现有记录并返回与最多属性匹配的记录。
例子:
A = 1
B = 1
C = 1
D = f
A | B | C | D
----+-----+-----+----
1 | 1 | 9 | f <
2 | 3 | 1 | g
3 | 4 | 2 | h
2 | 5 | 8 | j
3 | 6 | 5 | h
第一行将是我要查找的行,因为它具有最匹配的值。我认为它不需要计算与值的任何接近度,因为那样第 2 行可能更匹配。
【问题讨论】:
标签:
algorithm
search
theory
【解决方案1】:
遍历每一行,在字段匹配的行得分上加一(字段一的得分为 2),完成后,您将获得一个可以排序的得分结果集。
【解决方案2】:
基本算法可能如下所示(在 java 伪代码中):
int bestMatchIdx = -1;
int currMatches = 0;
int bestMatches = 0;
for ( int row = 0 ; row < numRows ; row++ ) {
currMatches = 0;
for ( int col = 0 ; col < numCols ; col++ ) {
if ( search[col].equals( rows[ row ][ cols] ))
currMatches++;
}
if ( currMatches > bestMatches ) {
bestMatchIdx = row;
bestMatches = currMatches;
}
}
这假设您有一个要比较的 equals 函数,并且数据存储在一个二维数组中。 'search' 是用于比较所有其他行的参考行。