解决循环组合程序问题的程序

FDR*_*DRH 7 javascript algorithm math combinatorics node.js

我了解如何通过手动问题来完成此操作,但我想创建一个 Javascript 程序来为 (c,r) 完成此操作,其中 c 是容器,r 是岩石。

设置 你有 4 块相同类型的难以区分的岩石。您还有 10 个容器。每个容器可以装 0 块石头或 1 块石头。每种排列都需要使用所有 4 块岩石,每种排列都需要留下 6 个 0。

我相信基于组合生成器,应该有 210 种可能性 (10!)/ (4! * (10-4)!) 附近的某个地方。

例如,这些是可能性的例子:

1111000000
1110100000
1110001000
0000001111
0101010100
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是一个 javascript 函数,它将吐出 210 个数组,这样它就可以[1,1,1,1,0,0,0,0,0,0]输入许多岩石和容器。

ble*_*lex 3

我尝试了 @JonTrent 的方法(从02^c - 1),这是一个非常聪明的方法:

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!`);
Run Code Online (Sandbox Code Playgroud)