生成所有可能的真/假组合

mor*_*sen 4 javascript arrays combinations boolean truthtable

我想创建一个包含三个变量的所有可能组合的数组,这些变量可以是真或假(即8种可能的组合).

我试图在此图像的左上角创建立方体

在此输入图像描述

所以输出应该是这样的

points = [
  // first square
  {
    id: '000',
    truths: [false, false, false]
    position: [0, 0]
  },
  {
    id: '100',
    truths: [true, false, false]
    position: [5, 0]
  },
  {
    id: '010',
    truths: [false, true, false]
    position: [0, 5]
  },
  {
    id: '110',
    truths: [true, true, false]
    position: [5, 5]
  },
  // second square
  {
    id: '001',
    truths: [false, false, true]
    position: [2.5, 2.5]
  },
  {
    id: '101',
    truths: [true, false, true]
    position: [7.5, 2.5]
  },
  {
    id: '011',
    truths: [false, true, true]
    position: [2.5, 7.5]
  },
  {
    id: '111',
    truths: [true, true, true]
    position: [7.5, 7.5]
  },
];

lines = [
  { from: '000', to: '100' },
  { from: '000', to: '010' },
  { from: '000', to: '001' },

  { from: '100', to: '101' },
  { from: '100', to: '110' },

  { from: '001', to: '101' },
  { from: '001', to: '011' },

  { from: '101', to: '001' },
  { from: '101', to: '111' },

  ...
]
Run Code Online (Sandbox Code Playgroud)

我不知道如何通过所有可能的真值来创造这些观点.

一种方法可以是使用for循环

for (var i=0; i<Math.pow(2, 3); i++) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

但它并没有帮助我分配可能的真值.

ASD*_*rte 8

计算机中的所有东西都是二进制的.你不需要任何花哨Math.pow或类似的东西.

for (let i = 0; i < 1 << 3; i++) {
  console.log([!!(i & (1<<2)), !!(i & (1<<1)), !!(i & 1)]);
}
Run Code Online (Sandbox Code Playgroud)

虽然这看起来很好而且很短,但我实际上并不是!!魔术数字的粉丝.我写这些片段的时候总是堕落.因此会尝试给出一个稍微清洁的版本:

const AMOUNT_OF_VARIABLES = 3;

for (let i = 0; i < (1 << AMOUNT_OF_VARIABLES); i++) {
  let boolArr = [];
  
  //Increasing or decreasing depending on which direction
  //you want your array to represent the binary number
  for (let j = AMOUNT_OF_VARIABLES - 1; j >= 0; j--) {
    boolArr.push(Boolean(i & (1 << j)));
  }
  
  console.log(boolArr);
}
Run Code Online (Sandbox Code Playgroud)