0

Given n variables I want to create decimals which equal all the possible binary variations in a truth table. e.g.

For a,b and c let:

a = 11110000 (240)
b = 11001100 (204)
c = 10101010 (170)

For p and q let:

p - 1100 (12)
q - 1010 (10)

I have worked out a formula to create the first number in any set, like so:

n = number of variables
x = 2^n

decimal = (2^x) - (2^(x/2));

I have implemented this in JavaScript like so:

var vars = ["a", "b", "c"];
var bins = [];

for (var i = 0; i < vars.length; i++) {
    var rows = 1 << vars.length;
    bins[i] = (1 << rows) - (1 << ((rows) / 2));
    console.log(bins[i].toString(2)); // logs 11110000
}

I can't work out how to calculate the rest of the numbers, does anyone know a formula to do this?

George Reith
  • 13,132
  • 18
  • 79
  • 148
  • if you sweep from 0 to n in decimals, the toString(2) conversions should hit every possible combo along the way. – dandavis Oct 23 '13 at 15:42
  • @dandavis That doesn't work. 0 - 3 in binary is `00`, `01`, `10`, `11`. Sure I could easily write this alternating 1's and 0's however the computation time grows exponentially and that is not good. I want to find a mathematical formula that means I don't have to create monstrously large loops. – George Reith Oct 23 '13 at 15:46

1 Answers1

0

I have found a solution however it does require a nested loop, this is not ideal as it means the computational time grows exponentially as the vars array grows.

I'm starting to think it isn't possible without looping.

Here is my final code. I have no idea how to write it as a mathematical formula so I won't bother.

var vars = ["a", "b", "c"];
var bins = [];

for (var i = 0; i < vars.length; i++) {
    var rows = 1 << vars.length;
    var max = (1 << rows) - 1;
    var diff = (1 << ((rows) / (2 << i))) - 1;
    var output = max - diff;

    var iterations = (1 << i);
    var step = 1 << (vars.length - i);
    for (var j = 1; j < iterations ; j++) {
        output -= (diff << (step * j)); 
    }

    bins[i] = output;

    console.log(bins[i].toString(2));
}

http://jsfiddle.net/RbPVx/1/

George Reith
  • 13,132
  • 18
  • 79
  • 148