获取2D数组(n x n)中0和1的所有可能组合

时间:2020-04-06 08:05:20

标签: javascript arrays combinations

我正在尝试生成一个方法,该方法在JS的2d平方数组中返回由2组成的每个2d数组的数组。基本上,这是与此相同的问题:Make every possible combination in 2D array

但是在Javascript中,不带包,并添加一个用于数组大小的参数。像是2x2会是:

let arr = new Array(2).fill(0).map(() => new Array(2).fill(0))
combinations(arr, 2) { ... }

returns : 
[
    [ 
        [0, 0],
        [0, 0]
    ],
    [
        [0, 0],
        [0, 1]
    ],
    [...],
    [
        [1, 1],
        [1, 1]
    ]
]

我尝试了递归,但没有成功,将不胜感激。

编辑:

我正在尝试= g编写一个递归函数来解决此问题。

现在,我有这种方法:

let arr = new Array(2).fill(0).map(() => new Array(2).fill(0))
const generateCombination = (arr, n) => {
    let ret = [];
    let tmp;
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < n; j++) {
        ret.push(arr)
        arr[i][j] = 1;
        generateCombination(arr.slice(), n-1)
      }
    }
    return ret;
  };

产生此输出:

[
  [ [ 1, 1 ], [ 1, 1 ] ],
  [ [ 1, 1 ], [ 1, 1 ] ],
  [ [ 1, 1 ], [ 1, 1 ] ],
  [ [ 1, 1 ], [ 1, 1 ] ],
]

1 个答案:

答案 0 :(得分:1)

有趣的是,参数 n 的不同组合可以表示为数字 0 到数字 2 n <的所有二进制序列。 sup> 2 -1

由于我们正在处理潜在的大数字,因此以下实现使用新的BigInt数据类型来表示这些数字。它使用每个数字,将二进制字符串填充到固定长度,然后将字符串分块为二维数组。

性能可能并不惊人,但是我认为这是一种有趣的方法。

const combinations = (n) => {
  const bits = n ** 2;
  const max = 2n ** BigInt(bits);
  const result = [];
  
  for (let i = 0n; i  < max; i++) {
    const s = i.toString(2).padStart(bits, '0');
    
    result.push([...s].map(Number).reduce((a, _, i, array) => (i % n)
        ? a
        : [...a, array.slice(i, i + n)], []));
  }
  return result;
}

console.log(combinations(2));


注意:BigInt是ECMAScript 2020功能,因此您的行驶里程可能会有所不同。

相关问题