javascriptarraysbooleancombinationstruthtable

Generating all possible true/false combinations


I want to create an array of all possible combinations of three variables that can either be true or false (i.e. 8 possible combinations).

I am trying to create the cube in the top left corner at this image

enter image description here

So the output should be something like

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

  ...
]

I don't know how to go through all possible truth values and create these points.

One approach could be to use a for loop

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

but it doesn't help me assigning the possible truth values.


Solution

  • Everything in a computer is already binary. You don't need any fancy Math.pow or similar.

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

    While this looks nice and short, i am actually not a fan of !! or magic numbers. I always fall for these tricks when writing snippets though. Therefore will attempt to give a slightly cleaner version:

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