我正在尝试提出一个匹配3个属性的匹配算法,我无法想到一个有效的解决方案。这是我的算法的伪代码
该算法执行以下操作:
似乎这个算法只是重复自己,如果我添加另一个值来匹配,那么这个算法会很快变得非常大。
//try to match on criteria 1
if results exist for match on criteria 1 {
//try to match on criteria 1 & 2
if results exist for match on criteria 1 & 2 {
//try to match on criteria 3
if result exist for match on criteria 1,2,3 {
return results for match on 1,2,3
}
else
return results for match on 1,2
}
else
return results for match on 1
}
//try to match on criteria 2
else if results exist for match on criteria 2 {
//try to match on criteria 2 & 3
if result exist for match on criteria 2,3 {
return results for match on 2,3
}
else
return results for match on 2
}
//try to match on criteria 3
else if results exist for match on criteria 3 {
return results for match on 3
}
else {
no match
}
有没有更好的方法呢?好像是
答案 0 :(得分:1)
如果我理解正确的话,这是Javascript中的一个实现。
function filter(arr, condition) {
var retval = [];
for (i in arr) if (condition(arr[i])) retval.push(arr[i]);
return retval;
}
function first_match(arr, conditions) {
if (conditions.length == 0) return("No match");
var initial_arr = Array.prototype.slice.call(arr);
var prev_arr;
var i = 0;
for (; i < conditions.length && arr.length != 0; i++) {
prev_arr = Array.prototype.slice.call(arr);
arr = filter(arr, conditions[i]);
}
if (i <= 1 && arr.length == 0) return first_match(initial_arr, Array.prototype.slice.call(conditions, 1));
else if (i == conditions.length && arr.length != 0) return arr;
else return prev_arr;
}
var conditions = [function(x) { return x > 3; },
function(x) { return x % 2 == 0; },
function(x) { return Math.sqrt(x) % 1 == 0; }];
var example1 = [1,2,3,4,5,6,7,8,9,10];
console.log(first_match(example1, conditions)); // [4] - all three hold
var example2 = [1,2,3,5,6,7,8,9,10];
console.log(first_match(example2, conditions)); // [6, 8, 10] - First two hold
var example3 = [5, 7, 9];
console.log(first_match(example3, conditions)); // [5, 7, 9] - First one holds
var example4 = [-2, 0, 2];
console.log(first_match(example4, conditions)); // [0] - 2 & 3 hold
var example5 = [-2, 2];
console.log(first_match(example5, conditions)); // [-2, 2] - Only 2 holds
var example6 = [1];
console.log(first_match(example6, conditions)); // [1] - Last one holds
var example7 = [-1];
console.log(first_match(example7, conditions)); // "No match" - None hold