Day02: Matrix and Longest String in Array (In another life)

Day02: Matrix and Longest String in Array (In another life)

MILESTONE 1: Complete Arcade Intro CodeSignal

DONE: 9/60

Day02: I solve 2 code challenges in arcade. (And today I only have 1h, not 2hrs as plan. Cannot commit as plan just in day 2. Will try more on next day)

Here is what I learn:

Challenge 5: matrixElementsSum

image.png

Here is my solution:

function matrixElementsSum(matrix) {
  let totalPoint = 0;
  let isValidToAdd = true;
  matrix = matrix[0].map((_, colIndex) => matrix.map((row) => row[colIndex]));
  matrix.forEach((row, rowIndex) => {
    isValidToAdd = true;
    row.forEach((el, i) => {
      if (el == 0) {
        isValidToAdd = false;
      } else if (isValidToAdd) {
        totalPoint += el;
      }
    });
  });
  return totalPoint;
}

Based on the challenge, I try to inverse matrix in JS. Here is what I search for help: stackoverflow.com/questions/17428587/transp..

Then I loop through it easily.

Here is highest point solution in JS:

function matrixElementsSum(matrix) {
  for (var r = 0, j = 0; j < matrix[0].length; j++) {
    for (var i = 0; i < matrix.length; i++) {
      if (matrix[i][j] === 0) break;
      else r += matrix[i][j];
    }
  }
  return r;
}

What I learn here:

  • I do not need to inverse array for this problem.
  • I learn how to interact with 2 dimensional array and mindset how to loop through column of it.
  • This is basic problem in matrix. I will based on this to solve other problem with matrix.

Challenge 6: allLongestStrings

image.png

Here is my solution:

function allLongestStrings(inputArray) {
  let rsArr = [];
  inputArray.forEach((string, i) => {
    if (i == 0) {
      rsArr.push(string);
    } else if (string.length > rsArr[0].length) {
      rsArr = [];
      rsArr.push(string);
    } else if (string.length == rsArr[0].length) {
      rsArr.push(string);
    }
  });
  return rsArr;
}

This kinda not hard. Just basic loop. First of all, I try to use reduce but cannot handle for initial data for accumulator.

Here is highest point solution in JS:

function allLongestStrings(inputArray) {
  "use strict";
  let maxSize = Math.max(...inputArray.map((x) => x.length));
  return inputArray.filter((x) => x.length === maxSize);
}

What I learn here:

  • Again, I forget to use the power of Math.max().
  • There are 2 times I see Math.max() combine with array.map(). This combination is awesome.
  • But I think this time my solution is maybe good, because I just use 1 loop. In highest point, it's clean but use 2 loops.

I done for today. I hope tomorrow will be better.

#inanotherlife