[英]How to effectively match on multiple values
我試圖提出一種匹配算法,可匹配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
}
有什么更好的方法嗎? 這好像是
如果我正確理解,這是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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.