jacekwilczynski

Matrix Diagonals Sum Difference

Aug 3rd, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function isRectangular(rows) {
  2.     if (rows.length > 0) {
  3.         const establishedWidth = rows[0].length;
  4.         return rows.every(row => row.length === establishedWidth);
  5.     }
  6.  
  7.     throw Error("Can't determine the shape of an empty structure. There needs to be at least one row.");
  8. }
  9.  
  10. class Matrix {
  11.     constructor(rows) {
  12.         if (!isRectangular(rows)) {
  13.             throw Error("A matrix has to have the same number of columns in each row.");
  14.         }
  15.  
  16.         this.width = rows[0].length;
  17.         this.height = rows.length;
  18.         this.rows = rows;
  19.     }
  20.  
  21.     getValue({ x, y }) { return this.rows[y] && this.rows[y][x]; }
  22.  
  23.     isValidPosition({ x, y }) {
  24.         return x >= 0 && x < this.width &&
  25.             y >= 0 && y < this.height;
  26.     }
  27.  
  28.     reduce({
  29.         reduceCallback,
  30.         initialValue: accumulator = 0,
  31.         startingPosition: position,
  32.         traversalMethod: getNextPosition
  33.     }) {
  34.         while (this.isValidPosition(position)) {
  35.             accumulator = reduceCallback(accumulator, this.getValue(position));
  36.             position = getNextPosition(position);
  37.         }
  38.  
  39.         return accumulator;
  40.     }
  41. }
  42.  
  43. const toBottomRight = ({ x, y }) => ({ x: x + 1, y: y + 1 });
  44. const toBottomLeft = ({ x, y }) => ({ x: x - 1, y: y + 1 });
  45.  
  46. const sum = (a, b) => a + b;
  47.  
  48. function diagonalDifference(arr) {
  49.     const matrix = new Matrix(arr);
  50.  
  51.     const ltr = matrix.reduce({
  52.         reduceCallback: sum,
  53.         startingPosition: { x: 0, y: 0 },
  54.         traversalMethod: toBottomRight
  55.     });
  56.  
  57.     const rtl = matrix.reduce({
  58.         reduceCallback: sum,
  59.         startingPosition: { x: matrix.width - 1, y: 0 },
  60.         traversalMethod: toBottomLeft
  61.     });
  62.  
  63.     return Math.abs(ltr - rtl);
  64. }
Advertisement
Add Comment
Please, Sign In to add comment