dimanche 12 février 2017

Per-element array operation on multidimensional matrix

Vote count: 0

I'm creating a 2D matrix in javascript, where each element in that matrix is an empty array.

The problem is, whenever I try to push to one of the elements in the matrix, the push gets applied to the entire matrix, not the specific element.

Here is the code:

function createMatrix(numrows, numcols, initialValue = []) {
   var matrix = []; var row = [];
   while (numcols--) row[row.length] = initialValue;
   while (numrows--) matrix[matrix.length] = row.slice();
   return matrix;
};

function printMatrix(matrix) {
   var output = '';
   for (var i = 0; i < matrix.length; i++) {
       output += '[';
       for (var j = 0; j < matrix[i].length; j++) {
           output += '  ' + matrix[i][j];
       }
       output += '  ]\n';
   }
   console.log(output);
};

// Example code
var A = createMatrix(3,6, []);
printMatrix(A)

// This is the output:
// [              ]
// [              ]
// [              ]

// For example, we now try to add number 7 to the empty array at [1][2]
A[1][2].unshift(7);

// Let's see how the matrix looks like:
printMatrix(A)
// [  7  7  7  7  7  7  ]
// [  7  7  7  7  7  7  ]
// [  7  7  7  7  7  7  ]

The above matrix is wrong, it should look like the following matrix:

// [                    ]
// [        7           ]
// [                    ]

Your help is greatly appreciated. Thank you.

asked 37 secs ago

Let's block ads! (Why?)



Per-element array operation on multidimensional matrix

Aucun commentaire:

Enregistrer un commentaire