生成所有可能的单词(“ true”,“ false”)二进制组合 [英] Generating all possible binary combinations in words ('true' 'false') performance

查看:129
本文介绍了生成所有可能的单词(“ true”,“ false”)二进制组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找以下脚本的性能改进。我很确定它可以进行实质性的修改,因为它是我想到的第一件事,所以我做了它,这只是出于我要寻找的演示目的。

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

我要寻找的是生成单词集对于所有可能的组合,这些组合实际上是在执行上述二进制操作。 ( runner(2); 会产生 false false false true true假 true真),我正在寻找可以让我到达这一点的快速闪电算法。 / p>

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.

推荐答案

尝试直接操作位,而不进行多余的字符串转换。

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

就记录而言,这可能会比较慢,但方法更好:

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

这篇关于生成所有可能的单词(“ true”,“ false”)二进制组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆