algorithm - How to effectively match on multiple values -
i trying come matching algorithm matches on 3 attributes , can't think of effective solution. here psuedocode algorithm
the algorithm following:
- check if there match on first criteria.
- if there match on first criteria try narrow match down based on other 2 criterias.
- if there no match on first criteria, try make match on second criteria.
- if there match on second criteria, try narrow match down based on last criteria.
- etc...
it seems algorithm repeats itself, , if add value match on, algorithm grows large real quickly.
//try match on criteria 1 if results exist match on criteria 1 { //try match on criteria 1 & 2 if results exist match on criteria 1 & 2 { //try match on criteria 3 if result exist match on criteria 1,2,3 { return results match on 1,2,3 } else return results match on 1,2 } else return results match on 1 } //try match on criteria 2 else if results exist match on criteria 2 { //try match on criteria 2 & 3 if result exist match on criteria 2,3 { return results match on 2,3 } else return results match on 2 } //try match on criteria 3 else if results exist match on criteria 3 { return results match on 3 } else { no match } is there better way this? seems
here implementation in javascript if understand correctly.
function filter(arr, condition) { var retval = []; (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 = 0; (; < 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; } examples
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] - 3 hold var example2 = [1,2,3,5,6,7,8,9,10]; console.log(first_match(example2, conditions)); // [6, 8, 10] - first 2 hold var example3 = [5, 7, 9]; console.log(first_match(example3, conditions)); // [5, 7, 9] - first 1 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] - 2 holds var example6 = [1]; console.log(first_match(example6, conditions)); // [1] - last 1 holds var example7 = [-1]; console.log(first_match(example7, conditions)); // "no match" - none hold
Comments
Post a Comment