2014-01-22 110 views
0

我有以下JavaScript代碼:組合多個二維數組

function Board() { 
    // 2d array of 'Pieces' 
    this.Map = [ 
    [new Piece(), new Piece(), new Piece()], 
    [new Piece(), new Piece(), new Piece()], 
    [new Piece(), new Piece(), new Piece()] 
    ]; 

    // return full 9x9 2d integer array 
    this.GetDetailedMap = function() { 
    //? 
    } 
} 

function Piece() { 
    //2d array of integers 
    this.Layout = [ 
    [1,0,1], 
    [0,0,0], 
    [1,0,1] 
    ] 
} 

function DifferentPiece() { 
    //2d array of integers 
    this.Layout = [ 
    [1,0,1,1], 
    [0,0,0,0], 
    [0,0,0,0], 
    [1,0,1,1], 
    ] 
} 

GetDetailedMap()什麼是應該做是返回一個9x9的二維數組包括該佈局的每一塊右索引處。

所有的'片'佈局總是正方形。所有作品都可以放大,例如:4x4,6x6等。一件3x3和另外4x4應該是不可能的。

我該如何實現該功能?

編輯: 我接近自己解決它,但我有一些錯誤,我的代碼並不像接受的答案那樣整齊。

+2

你怎麼希望他們結合?有很多方法可以將2d數組組合。你遇到了什麼問題?你怎麼試圖把它們結合起來,爲什麼它不起作用? –

回答

0

這應做到:

this.GetDetailedMap = function flatMap() { 
    var piecesize = this.Map[0][0].Layout.length; 
    var detailedMap = []; 
    for (var i=0; i<this.Map.length; i++) { 
     var mapRow = this.Map[i]; 
     for (var j=0; j<piecesize; j++) { 
      var detailedRow = []; 
      for (var k=0; k<mapRow.length; k++) { 
       var pieceRow = mapRow[k].Layout[j]; 
       for (var l=0; l<pieceRow.length; l++) { 
        detailedRow.push(pieceRow[l]); 
       } 
      } 
      detailedMap.push(detailedRow); 
     } 
    } 
    return detailedMap; 
} 
+0

我自己接近解決它,但你的代碼更清潔!非常感謝!我有同樣的觀點。 – Ruud