2014-01-22 103 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