我想创建一个包含三个变量的所有可能组合的数组,这三个变量可以是真也可以是假(即 8 种可能的组合)。
我正在尝试在这张图片的左上角创建立方体
所以输出应该是这样的
points = [
// first square
{
id: '000',
truths: [false, false, false]
position: [0, 0]
},
{
id: '100',
truths: [true, false, false]
position: [5, 0]
},
{
id: '010',
truths: [false, true, false]
position: [0, 5]
},
{
id: '110',
truths: [true, true, false]
position: [5, 5]
},
// second square
{
id: '001',
truths: [false, false, true]
position: [2.5, 2.5]
},
{
id: '101',
truths: [true, false, true]
position: [7.5, 2.5]
},
{
id: '011',
truths: [false, true, true]
position: [2.5, 7.5]
},
{
id: '111',
truths: [true, true, true]
position: [7.5, 7.5]
},
];
lines = [
{ from: '000', to: '100' },
{ from: '000', to: '010' },
{ from: '000', to: '001' },
{ from: '100', to: '101' },
{ from: '100', to: '110' },
{ from: '001', to: '101' },
{ from: '001', to: '011' },
{ from: '101', to: '001' },
{ from: '101', to: '111' },
...
]
我不知道如何遍历所有可能的真值并创建这些点。
一种方法是使用for循环
for (var i=0; i<Math.pow(2, 3); i++) {
...
}
但这并不能帮助我分配可能的真值。
最佳答案
计算机中的一切都已经是二进制的。您不需要任何花哨的 Math.pow
或类似的东西。
for (let i = 0; i < 1 << 3; i++) {
console.log([!!(i & (1<<2)), !!(i & (1<<1)), !!(i & 1)]);
}
虽然这看起来不错而且很短,但实际上我不是 !!
或魔术数字的粉丝。不过,在编写代码片段时,我总是爱上这些技巧。因此将尝试提供一个稍微干净的版本:
const AMOUNT_OF_VARIABLES = 3;
for (let i = 0; i < (1 << AMOUNT_OF_VARIABLES); i++) {
let boolArr = [];
//Increasing or decreasing depending on which direction
//you want your array to represent the binary number
for (let j = AMOUNT_OF_VARIABLES - 1; j >= 0; j--) {
boolArr.push(Boolean(i & (1 << j)));
}
console.log(boolArr);
}
关于javascript - 生成所有可能的真/假组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39734887/