2017-07-27 40 views
1

的3D陣列假設一個三維矩陣的字符串在string的形式進行編碼,如下所示:轉化編碼布爾

src = "1 0 0 1 1 1 0 0 0 0 0 1" 

...其中3個空格分開的層,空格分隔行,並且一個空格分隔列。

最終,我的目標是能夠把它轉化到bool一個三維矩陣:

console.log(result) // [[[1, 0, 0], [1, 1, 1]], [[0, 0, 0], [0, 0, 1]]] 

如何使用純功能性的方法,我變換src獲得result?我正在使用Lodash

回答

1

我最好的選擇就是遞歸函數,但事先向可以在單線程中做到這一點的人提前感謝。鑑於:

const src = "1 0 0 1 1 1 0 0 0 0 0 1" 

讓我們來定義breakStuff/2爲:

function breakStuff(spaces, input) { 
    if (spaces.length == 0) return parseInt(input) 
    return _.map(_.split(input, _.first(spaces)), i => breakStuff(_.tail(spaces), i)) 
} 

用例:

breakStuff([' ', ' ', ' '], src) 

將返回:

​​​​​​​​​​[ [ [ 1, 0, 0 ], [ 1, 1, 1 ] ], [ [ 0, 0, 0 ], [ 0, 0, 1 ] ] ]​​​​​ 

補遺:根據你的規範 - 雖然你自己的例子使用0's和1's - 結果應該由bool組成。對於這一點,只是更改爲以下行:

if (spaces.length == 0) return input == '1' 

這將返回:

[ [ [ true, false, false ], [ true, true, true ] ],​​​​​ 
​​​​​ [ [ false, false, false ], [ false, false, true ] ] ]​​​​​ 
3

爲什麼lodash?使用JS map

src.split(" ") 
    .map(layer => layer.split(" ") 
    .map(rows => rows.split(" ") 
    .map(item => +item))); 
// [ [ [ 1, 0, 0 ], [ 1, 1, 1 ] ], [ [ 0, 0, 0 ], [ 0, 0, 1 ] ] ]