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

时间:2016-09-27 21:51:24

标签: javascript arrays boolean combinations truthtable

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

我正在尝试在此图片的左上角创建多维数据集

enter image description here

所以输出应该是

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' },

  ...
]

我不知道如何查看所有可能的真值并创建这些点。

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

for (var i=0; i<Math.pow(2, 3); i++) {
  ...
}

但它无法帮助我分配可能的真值。

4 个答案:

答案 0 :(得分:6)

计算机中的所有内容都已经是二进制的。您不需要任何花哨的Math.pow或类似的。

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

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

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);
}

答案 1 :(得分:2)

这很简单,只需将0到2**n-1之间的所有整数转换为二进制:

var n = 3,
    m = 1 << n;
for (var i = 0; i < m; i++) {
    var s = i.toString(2); // convert to binary
    s = new Array(n + 1 - s.length).join('0') + s; // pad with zeroes
    console.log(s);
}

以上代码是通用的;您可以将n更改为您想要的数字位。

答案 2 :(得分:2)

pow(2, n)个可能的值。

在二进制数系统中,数字可以简单地视为&#34;数组&#34;位:0 = [0,0,0],1 = [0,0,1],2 = [0,1,0],3 = [0,1,1],4 = [1,0,0],5 = [1,0,1] ,6 = [1,1,0],7 = [1,1,1]

遵循这个想法,最简单的方法是提取整数[0, pow(2, n) - 1]的位。以下代码是上述想法的直接实现:

function test()
{
   var n = 3;
   var k = (1 << n); // bit trick for pow(2, n)

   var truths = [];

   for (var i = 0; i < k; ++i)
   {
      truths[i] = [];

      for (var j = 0; j < n; ++j)
      {
         var value = (i >> j) & 1; // extract the j-th bit of i
         truths[i][j] = value;
      }

      console.log(truths[i]);
   }
}

答案 3 :(得分:1)

const boolCombo = size => {
  const buf = Array(1 << size)
  for (let i = buf.length; i--;) {
    buf[ i ] = Array(size)
    for (let j = size; j--;)
      buf[ i ][ j ] = +!!(i & 1 << j)
  }
  return buf
}

console.log(boolCombo(3))