Furman
Furman

Reputation: 2395

Square matrix transpose in Javascript

I'm trying to create square matrix transpose function in Javascript, but it doesn't work as expected. Function:

function transpose(){
  var tmpCells = cells;

  for(var i=0; i<boardHeight; i++){
    for(var j=0; j<boardWidth; j++){
      tmpCells[i][j] = cells[j][i];
    }
  }
  cells =  tmpCells;
  clearCells();
  drawCells();
}

creates weird output. Instead of new 2D array of original size, it misses some cells and instead array of objects it creates array of different size with circular bjects inside. How this can be fixed and what I'm doing wrong?

JS fiddle link: https://jsfiddle.net/Ls8jbho3/

Upvotes: 0

Views: 1330

Answers (2)

avidya
avidya

Reputation: 91

mathjs can do this. Here is the example :

var A = [[1, 2, 3], [4, 5, 6]];
math.transpose(A);               // returns [[1, 4], [2, 5], [3, 6]]

Upvotes: 0

Amadan
Amadan

Reputation: 198294

Because tmpCells = cells makes a new reference to an existing object rather than copying that object, tmpCells[i][j] = cells[j][i] is exactly the same as cells[i][j] = cells[j][i]. This is the source of all your problems.

Make sure your tmpCells does not share structure with cells, and the problem goes away:

function transpose(){
  var tmpCells = [];
  for(var i=0; i<boardHeight; i++){
    tmpCells[i] = [];
    for(var j=0; j<boardWidth; j++){
      tmpCells[i][j] = cells[j][i];
    }
  }
  cells =  tmpCells;
}

Upvotes: 2

Related Questions