Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top