Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all possible binary combinations in words ('true' 'false') performance

I am looking on performance improvement of the script below. I am pretty sure it can be substantially modified, I did it as it was first thing that came to my head and it is only for demonstration purposes on what I am looking for.

function pad(nn, width, z) {
    z = z || '0';
    nn = nn + '';
    return nn.length >= width ? nn : new Array(width - nn.length + 1).join(z) + nn;
}

var makeIntoBinary = function(ii, length) {
    return pad(ii.toString(2), length);
}

var makeIntoTrueFalse = function(binary) {
    var str = '';
    for (iii = 0; iii < binary.length; iii++) {
        if (binary[iii] == '0') {
            str += ' false';
        } else {
            str += ' true';
        }
    };
    console.log(str + ' ' + binary);
}

var runner = function(n) {
    var iter = Math.pow(2, n);
    for (i = 0; i < iter; i++) {
        makeIntoTrueFalse(makeIntoBinary(i, n));
    }
}

What I am looking for is to generate sets of words for all possible combinations which is essentially doing the binary above. (runner(2); would produce false false, false true, true false, true true) I am looking for lightning fast algorithm that gets me to this point.

like image 766
Matas Vaitkevicius Avatar asked May 10 '26 04:05

Matas Vaitkevicius


1 Answers

Try manipulating bits directly, without extraneous string conversions.

function combinations(n) {
  var r = [];
  for(var i = 0; i < (1 << n); i++) {
    var c = [];
    for(var j = 0; j < n; j++) {
      c.push(i & (1 << j) ? 'true' : 'false');  
    }
    r.push(c.join(' '));
  }
  return r;  
}

r = combinations(prompt('size?'));
document.write(JSON.stringify(r));

Just for the record, this is probably slower, but way nicer:

Number.prototype.times = function(fn) {
  var r = [];
  for(var i = 0; i < this; i++)
    r.push(fn(i));
  return r;
}

function combinations(n) {
  return (1 << n).times(function(i) {
    return n.times(function(j) {
      return Boolean(i & 1 << j);
    });
  });
}
like image 162
georg Avatar answered May 11 '26 17:05

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!