我试图为游戏SET生成卡片组,或者,对于那些不知道那是什么的人,我试图用表单中的独特元素填充数组[a, b, c, d]
,其中0 <= a, b, c, d <= 2
(81个元素)。所以,我想要[[0, 0, 0, 0,], [0, 0, 0, 1], ... , [2, 2, 2, 2]]
(顺序并不重要)。这是我到目前为止的代码:
var deck = [],
count = [0, 0, 0, 0];
for (var i = 0; i < 81; i++) { // go through all combos
deck.push(count); // append the current modification of count to deck
// increment count by 1, carrying "tens" if necessary
for (var j = 3; count[j] === 2; j--) {
// if the "digit" is 2, make it 0 since it overflows
count[j] = 0;
}
// j is the first "digit" of count that isn't already 2, so we add 1 to it
count[j]++;
}
相反,这似乎做的是用最后修改deck
填充count
数组;如果i
的上限是81,那么它是[0, 0, 0, 0]
,因为它一直翻转,如果你将边界更改为任何更低,它将相应地作出响应。为什么会这样?我犯了什么错误?
答案 0 :(得分:1)
请记住,您每次迭代都会将同一count
推送到deck
,这意味着任何计数更改都会反映到count
中的所有其他deck
因为他们都引用了相同的array
您可以使用.slice
克隆具有前一个count
中相同值的新数组。
var deck = [],
count = [0, 0, 0, 0];
for (var i = 0; i < 81; i++) { // go through all combos
// Clone a new array from previous one.
count = count.slice();
deck.push(count); // append the current modification of count to deck
// increment count by 1, carrying "tens" if necessary
for (var j = 3; count[j] === 2; j--) {
// if the "digit" is 2, make it 0 since it overflows
count[j] = 0;
}
// j is the first "digit" of count that isn't already 2, so we add 1 to it
count[j]++;
}
console.log(deck);
&#13;