簡體   English   中英

將數組添加到數組列表為空

[英]adding arrays to a list of arrays is blank

因此,我正在編寫一種方法來遞歸查找數字列表的所有排列。

我將每次運行的結果(即數字數組)添加到更大的combos數組中。 但是,組合變得像這樣用空數組填充: [[],[],[]]代替[[1,2,3],[3,2,1],[2,3,1] ...]但我知道組合正在生成

這是我所擁有的:

var combos = [];
permuteHelper([1,2,3],[]);
console.log(combos); //printing blank array or arrays [[],[]]
function permuteHelper(list, combination){

    if(list.length == 0){
        combos.push(combination); //ERROR: combos only holds blank arrays (e.g. [[],[]] )
        console.log(combination); //although this is printing correct list after each recursive run (e.g. [3,2,1] )
    }
    for(var i = 0; i < list.length; i++ ){

        //pick a digit
        var digit = list[i];
        list.splice(i,1); //remove the character from the array
        combination.push(digit);

        //recursively keep picking
        permuteHelper(list, combination);

        //backtrack and put the digit back for next time
        list.splice(i,0,digit);
        combination.pop();
    }

}

我嘗試使組合成為非全局的並且更新了函數頭

function permuteHelper(list, combination,combos)

但是組合仍然無法正確填充。 我是JS新手,不確定我缺少什么。

當您將combination作為函數的參數時,它將被視為參考。 combination任何更改都會更改原始變量。 您將該引用permuteHelperpermuteHelper每個新調用,因此始終修改原始數組。

只需進行少量代碼更改的原始解決方案是:

var combos = [];
permuteHelper([1, 2, 3], [], []);

function permuteHelper(list, _combination) {
    var combination = Object.assign([], _combination);
    if (list.length == 0) {
        combos.push(combination); //this only has a blank array of 
        arrays(e.g. [[], []])
        console.log(combination); //prints correct permuted list after each recursive trial (e.g. [3,2,1] )
    }
    for (var i = 0; i < list.length; i++) {

        //pick a digit
        var digit = list[i];
        list.splice(i, 1); //remove the character from the array
        combination.push(digit);

        //recursively keep picking
        permuteHelper(list, combination, combos);

        //backtrack and put the digit back for next time
        list.splice(i, 0, digit);
        combination.pop();
    }
}

這樣,您可以根據參數_combination創建一個新的對象combination ,可以根據需要對其進行修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM