2015-03-19 147 views
0

我想創建一個使用兩個數組的樹 - 第一個數組包含需要轉換爲層次結構/樹/嵌套數組的整數,第二個數組包含觸發分支的數字。如何在JavaScript中使用2個一維數組創建層次結構樹?

我已經成功地將第一個數組切片爲分支作爲基本測試,但我認爲我錯過了正確嵌套數組所需的遞歸函數makeBranch中的某些內容。

這工作:

var sequence = [0, 2, 1, 3, 4, 9, 7, 14, 13, 15, 23, 21, 22, 17, 20, 19, 17, 23, 24, 16, 11, 6, 10, 5], 
breaks = [ 0, 17, 23 ]; 

var tree = []; 
for (var i = 0, imax = sequence.length; i<imax; ++i) { 
    var val = sequence[i]; 
    if (breaks.lastIndexOf(val) != -1) { 
     tree.push([]); 
    } 
    tree[tree.length-1].push(val); 
} 
console.log(tree); // **** First test - passes 

使用相同的陣列,它產生一個非常奇怪的結果:

var tree = makeBranch(sequence, 0, breaks); 
console.log(tree); // **** Second test - fails 

function makeBranch(sequence, i, breaks) { 

    var branch = []; 
    for (var imax = sequence.length; i<imax; ++i) { 
     var val = sequence[i]; 
     if (breaks.lastIndexOf(val) != -1) { 
      branch.push(makeBranch(sequence.slice(i+1), i+1, breaks)); 
     } 
     branch.push(val); 
    } 

    return branch; 

} 

基本上,我希望把這個數組:

[0, 2, 1, 3, 4, 9, 7, 14, 13, 15, 23, 21, 22, 17, 20, 19, 17, 23, 24, 16, 11, 6, 10, 5] 

插入此(或類似物):

[0, 2, 1, 3, 4, 9, 7, 14, 13, 15, [23, 21, 22, [17, 20, 19], [17]], [23, 24, 16, 11, 6, 10, 5]] 

任何幫助,將不勝感激。

+0

算法應該如何知道其中一箇中斷應該在父對象上啓動一個新分支,而不是在它正在建立的當前分支上?即如何知道結果不應該是:[0,2,1,3,4,9,7,14,13,15,[23,21,22,[17,20,19, 17,[23,24,16,11,6,10,5]]]]'? – JLRishe 2015-03-19 04:34:46

+0

項目規格在一夜之間發生了變化,所以這個問題剛剛解決了。爲了以防萬一,我會保留Simone的代碼。 – rory 2015-03-19 22:18:24

回答

0
var tree = function (seq, breaks) { 
    var res = [], n; 
    for(var i = 0; i < seq.length;) { 
     if(breaks.indexOf(seq[i]) != -1) { 
      for(var j = i+1; j < seq.length; j++) { 
       if(breaks.indexOf(seq[j]) != -1) { 
        break; 
       } 
      } 
      n = j; 
      var branch = tree(seq.slice(i+1, n), breaks); 
      branch.unshift(seq[i]); 
      res.push(branch); 
      i+=branch.length; 
     } else { 
      res.push(seq[i]); 
      i++; 
     } 
    } 
    return res; 
} 

tree([0, 2, 1, 3, 4, 9, 7, 14, 13, 15, 23, 21, 22, 17, 20, 19, 17, 23, 24, 16, 11, 6, 10, 5], [0,17,23]) 

[[0, 2, 1, 3, 4, 9, 7, 14, 13, 15], [23, 21, 22], [17, 20, 19], [17], [23, 24, 16, 11, 6, 10, 5]]