【发布时间】:2017-02-05 16:32:12
【问题描述】:
我想创建一个包含三个变量的所有可能组合的数组,这些变量可以为真或假(即 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++) {
...
}
但这并不能帮助我分配可能的真值。
【问题讨论】:
-
有 2^n 个可能的值。如果你不想使用嵌套的 for 循环(你真的不应该),那么提取整数
0...2^n的位。truths中的n值将是整数的位。 -
我只是不明白如果您的订单是 0、4、2、3、1、5、7、8,二进制方法将如何帮助您。为什么不只使用数字。
-
@Redu 我不明白你在说什么。顺序无关紧要。所有从 0 到 8 的整数将代表 3 位,对应于 OP 类比中的
truths数组。 2^n 个整数 = 2^ntruths数组。在二进制中,数字可以被认为是位的“数组”:0=[0,0,0], 1=[0,0,1], 2=[0,1,0], 3=[0,1 ,1], 4=[1,0,0] , 5=[1,0,1], 6=[1,1,0], 7=[1,1,1]。
标签: javascript arrays boolean combinations truthtable