1

Below is my code.

Sample values for oddCells function are n = 2, m = 3, indices = [[0,1],[1,1]].

My incrementColumn helper function works fine. The forEach loop works on the inside but then the incremented values are not saved back into arr[row] for some reason.

Question is from LeetCode "Cells with Odd Values in a Matrix"

var incrementRow = (row, arr) => {
    arr[row].forEach((e) => e++);
}

var incrementColumn = (col, arr) => {
    arr.forEach((e) => e[col]++);
}

var oddCells = (n, m, indices) => {
    //Define our matrix
    let matrix = [];
    //Initialize matrix with zeroes
    for(let i = 0; i < n; i++) {
        matrix[i] = []
        for(let j = 0; j < m; j++) {
            matrix[i][j] = 0;
        }
    }
    console.log(matrix);
    //Iterate through indices array
    for(let i = 0; i < indices.length; i++) {
        incrementRow(indices[i][0], matrix);
        incrementColumn(indices[i][1], matrix);
    }
    console.log(matrix);
};
zarya
  • 29
  • 3
  • `arr[row].forEach((e) => e++);` does not do anything. You have to actually save the incremented value at the correct index: `arr[row] = arr[row].map(e => ++e);` – Đinh Carabus Feb 07 '20 at 16:25
  • If you want to use forEach: `arr[row].forEach((e, i) => arr[row][i] = ++e)` – Đinh Carabus Feb 07 '20 at 16:31
  • Hi, thanks for the response. I tried the map solution before, yet somehow the difference was the fact that I wrote ++e instead of e++... and now it works, do you know why that is? – zarya Feb 07 '20 at 16:42
  • @zarya take a look here in regards to the `++e` vs `e++` - https://stackoverflow.com/questions/16869020/pre-increment-vs-post-increment-in-array – goto Feb 07 '20 at 16:58

0 Answers0