Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program to solve Circular Combinatorics Program Problem

I understand how to do this by problem by hand, but I want to create a Javascript program to complete this for (c,r), with c being containers and r being rocks.

Setting You have 4 indistinguishable rocks of all the same type. You also have 10 containers. Each container can hold 0 rocks or 1 rock. All 4 rocks need to be used in every arrangement leaving 6 0s in each arrangement.

I believe there should be somewhere in the neighborhood of 210 possibilities (10!)/ (4! * (10-4)!) based on a combinations generator.

for example, these are examples of the possibilities:

1111000000
1110100000
1110001000
0000001111
0101010100

What I am looking for is a javascript function that will spit out the 210 arrays such that it is [1,1,1,1,0,0,0,0,0,0] with an input of a number of rocks and containers.

like image 742
FDRH Avatar asked Jun 28 '20 15:06

FDRH


1 Answers

I tried @JonTrent's way to do it (counting from 0 to 2^c - 1), this is a really clever way to do it:

function getCombinations(c, r) {
  const max = Math.pow(2, c);
  const res = [];
  for (let i = 0; i < max; i++) {
    const binary = i.toString(2);
    if (binary.split("1").length - 1 === r) {
      res.push(
        binary.padStart(c, '0')
              .split('')
              .map(n => parseInt(n, 10))
      );
    }
  }
  return res;
}

const res = getCombinations(10, 4);
// [
//  [0,0,0,0,0,0,1,1,1,1],
//  [0,0,0,0,0,1,0,1,1,1],
//  [0,0,0,0,0,1,1,0,1,1]
//  ...
// ]

document.body.innerHTML = `<pre>${res.map(x => x.join('')).join('\n')}</pre>`;
console.log(`${res.length} combinations found!`);
like image 101
blex Avatar answered Sep 29 '22 02:09

blex