Javascript-具有所有可能组合的字节字符串

Javascript - String of a Byte with all combinations possible

本文关键字:字节 字符串 组合 有可能 Javascript-      更新时间:2023-09-26

我有一个字符串,里面有一个字节("00001011"),现在我想得到一个数组,里面有1(acitve)"位"的所有可能组合,也可以作为"字节字符串"所以从

var bString="00001011"//传出字符串

到一个数组,其中包含所有字符串以及该"字节字符串"的所有可能组合,如-"00000001"、"00000011"、"0000010"等等

这可能吗?

提前感谢

function combinations( input ){
   var number = parseInt( input, 2 );
   var combinations = [];
   var zeroes = (new Array(input.length)).join(0);
   for(var i=1;i<=number;i++){
     if((i&number) == i){ combinations.push( i ) }
   }
   return combinations.map( function(dec){
      return  (zeroes + dec.toString(2)).substr( -zeroes.length-1 );
   });
}

http://jsfiddle.net/jkf7pfxn/3/

console.log( combinations("00001011") );
// ["00000001", "00000010", "00000011", "00001000", "00001001", "00001010", "00001011"]

其思想如下:将所有数字从1迭代到输入数字。如果当前数字AND输入数字返回当前数字,则两者在同一位置都具有1位。

在较小的数字"0101"(即5)上,其工作原理如下:

1 & 5 == 1(0001和0101)将1推向比赛。

2 & 5 == 0,(0010和0101)不匹配。

3 & 5 == 1,(0011和010

4 & 5 == 4(0100和0101)将4推向比赛。

5 & 5 == 5(0101和0102)将5推向比赛。

因此,0101的组合是10001)、20010)、40100)和50101)。

然后有一个用零填充数字的小技巧:

var zeroes = (new Array(input.length)).join(0); // gives a long enough string of zeroes

然后

 // convert to base 2, add the zeroas at the beginning, 
 // then return the last n characters using negative value for substring
 return (zeroes + dec.toString(2)).substr( -1 * zeroes.length);

由于11111111是255,所以只需循环所有值并将其转换为二进制

$(document).ready(function() {
  for (var i = 0; i < 256; i++) {
    $('#core').append('<div>' + dec2bin(i) + '</div>');
  }
  function dec2bin(dec) {
    return ('00000000' + (dec >>> 0).toString(2)).slice(-8);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='core'></div>

如果您想枚举1只能位于模式位置的所有二进制数组合,您可以编写一个简单的递归函数:

var input = "00010111";
var current = [];
function combinations()
{
    if (input.length === current.length)
    {
        var output = current.join('');
        if (parseInt(output, 2) !== 0) // exclude all-zeroes case
            document.body.innerHTML += output + "<br/>";
        return;
    }    
    
    current.push('0'); 
    combinations();
    current.pop();
    
    if (input[current.length - 1] === '1') 
    {
        current.push('1');
        combinations();
        current.pop();
    }
}
combinations();

该算法适用于任意长度的CCD_ 23
尽管它是一个递归,但它具有线性时间复杂性。