3

I'm trying to write a function in javascript that can devide x elements over y elements in every possible combination. I included a picture of what I want to achieve. It's some basic brute force I guess, but I can't figure out how I should write the loops. I hope somebody can help me. Thanks in advance

enter image description here

for the code. I don't have much yet, because what I tried didn't work.

But I have a globaly defined empty array which is X long. And I have another array full of THE SAME elements and want every combination of the array of length X containing the elements of array with length Y.

Bosiwow
  • 2,025
  • 3
  • 28
  • 46
  • can you convert the image to png format utleast we can see here below the question? – Praveen Apr 18 '14 at 10:44
  • 2
    Can you please post your code, even if either incomplete or not working? – Roberto Reale Apr 18 '14 at 10:44
  • possible duplicate of [permutations in javascript?](http://stackoverflow.com/questions/9960908/permutations-in-javascript) – adeneo Apr 18 '14 at 10:58
  • @adeneo It's not a duplicate. The question that you linked to only has a single array and produces an array of all the possible permutations of the input array (i.e. for an array of length `n` it produces `n!` permutations). This question is fundamentally different. – Aadit M Shah Apr 18 '14 at 11:00

1 Answers1

4

You are looking for combination. In your case n=x and k=y.By borrowing code from here, you can visualize it by this way:

var x = 7;
var y = 3;
comb(y,x).forEach(function(item){    
    var tr = $('<tr>');
    for(var i=0; i<x;++i){
        tr.append('<td>');
    }
    var chunks = item.split(" ");
    chunks.pop();
    chunks.forEach(function(index){
        tr.find("td").eq(+index).addClass("black");
    });
    $("table").append(tr);
});

DEMO

Engineer
  • 47,849
  • 12
  • 88
  • 91