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 binations 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.
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 binations 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.
1 Answer
Reset to default 10Try manipulating bits directly, without extraneous string conversions.
function binations(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 = binations(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 binations(n) {
return (1 << n).times(function(i) {
return n.times(function(j) {
return Boolean(i & 1 << j);
});
});
}