Program to solve Circular Combinatorics Program Problem
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!`);