javascript - Binomial sub arrays -
i have array n length. want take possible k (0
for example, if have a's length five:
[1,2,3,4,5]
and if k = 3, algorithm must give me b array.
[1,2,3 ] [1,2, 4 ] [1,2, 5] [1, 3,4 ] [1, 3, 5] [1, 4,5] [ 2,3,4 ] [ 2,3, 5] [ 2, 4,5] [ 3,4,5]
length of b equal n!/k!(n-k)!
('!' means factorial, newtons method)
i'm using javascript, in tags included it, it's algorithm, not necessary written in javascript.
below copy-paste 1 of projects. don't know if still works ;)
var choose = function choose_func(elems, len) { var result = []; (var i=0; i<elems.length; i++) { if (len == 1) { result.push([elems[i]]); } else { var remainingitems = choose_func(elems.slice(i+1, elems.length), len - 1); (var j=0; j<remainingitems.length; j++) result.push([elems[i]].concat(remainingitems[j])); } } return result; }; var result = choose([1,2,3,4,5], 3) /*result = [[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5], [1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]] */
Comments
Post a Comment