【发布时间】:2021-10-28 11:16:13
【问题描述】:
我一直在研究列出布尔值数组所有可能组合的算法。
例如,一个由两个布尔值组成的数组可以有以下组合: [真,真],[真,假],[假,真],[假,假]
我找到了几个使用位运算符的示例,虽然我查看了所用运算符的定义,但我仍然不了解它们在算法中的上下文用途。
我在下面列出了一个示例算法(来源:http://zacg.github.io/blog/2013/08/02/binary-combinations-in-javascript/),并带有注释来描述我在查看它们时看到的内容:
function binaryCombos(n){
var result = [];
for(y=0; y<Math.pow(2,n); y++){ // This cycles through the maximum number of combinations
(power of 2 because it's binary)
var combo = []; // combo for particular iteration, eventually pushed to result
for(x=0; x<n; x++){ // iterate over number of booleans in array
//shift bit and and it with 1
if((y >> x) & 1) // right shifts and then masks for 1? i.e. tests if it's odd??
combo.push(true); // I don't see how this ensures all combiantions are covered
else
combo.push(false); // I don't understand the criteria for pushing false or true :(
}
result.push(combo);
}
return result;
}
//Usage
combos = binaryCombos(3);
for(x=0; x<combos.length; x++){ // This looks like driver code so have been ignoring this
console.log(combos[x].join(','));
}
这是一个使用 n = 2 的示例:
y = 0 x = 0
0 >> 0 仍然为 0,因此当与 1 进行“与”运算时将评估为 false:
0000 0000 & 0000 0001 --> 0
'false' 推送到组合数组
y=0 x=1
0 >> 1 仍然为 0 并将 'false' 推送到组合数组
推送到结果:[false, false]
y=1 x=0
1 >> 0 等于 0000 0001 没有移位(?)所以 'anding' 与 1 将评估为真, 'true' 推送到组合数组
y=1 x=1
1 >> 1 与减半相同,但会 eval 为 0,因此 false 被推送到组合数组
推送到结果:[true, false]
y=2 x=0
2 >> 0 等于 false 被推送到组合数组为 0000 0010 & 0000 0001 = 0
y=2 x=1
2 >> 1 等于 true 被推送为 0000 0001 & 0000 0001 = 1
推送到结果:[false, true]
y=3 x=0
3 >> 0 等于 true 被推送到组合数组,因为 0000 0011 & 0000 0001 = 1
y=3 x=1
3 >> 1 等于 true 被推送到组合数组
推送到结果:[true, true]
返回结果:[[false, false], [true, false], [false, true], [true, true]]
我可以直观地看到嵌套循环将有助于解决排列问题,并且我可以认识到这已经得出了正确的答案,但看不到将 y 移动 x 和“与”之间的关系,并全面覆盖所有组合。
任何帮助表示赞赏!
【问题讨论】:
-
我知道您想在阅读完答案后对您所理解的内容做一些笔记,但这确实不属于问题部分。如果您想为未来的读者留下关于您的理解的注释,请将其发布为答案,而不是对您的问题的编辑。
标签: algorithm bitwise-operators bit-shift bitwise-and