Given an array or object with n keys, I need to find all combinations with length x .
Given x is a variable. binomial_coefficient(n,x) .
I am currently using this:
function combine(items) { var result = []; var f = function(prefix, items) { for (var i = 0; i < items.length; i++) { result.push(prefix + items[i]); f(prefix + items[i], items.slice(i + 1)); } } f('', items); return result; } var combinations = combine(["a", "b", "c", "d"]);
Output:
["a", "ab", "abc", "abcd", "abd", "ac", "acd", "ad", "b", "bc", "bcd", "bd", "c", "cd", "d"]
So, if I need a binomial coefficient x=3 of n=4 , I select all rows with a length of three. {abc, abd, acd, bcd}.
So, I am doing this in two steps.
Is there a more efficient algorithm with less complexity?
Link: Solution Efficiency (JSPerf)
javascript algorithm dynamic-programming memoization binomial-coefficients
Panos Kal.
source share