Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function isRectangular(rows) {
- if (rows.length > 0) {
- const establishedWidth = rows[0].length;
- return rows.every(row => row.length === establishedWidth);
- }
- throw Error("Can't determine the shape of an empty structure. There needs to be at least one row.");
- }
- class Matrix {
- constructor(rows) {
- if (!isRectangular(rows)) {
- throw Error("A matrix has to have the same number of columns in each row.");
- }
- this.width = rows[0].length;
- this.height = rows.length;
- this.rows = rows;
- }
- getValue({ x, y }) { return this.rows[y] && this.rows[y][x]; }
- isValidPosition({ x, y }) {
- return x >= 0 && x < this.width &&
- y >= 0 && y < this.height;
- }
- reduce({
- reduceCallback,
- initialValue: accumulator = 0,
- startingPosition: position,
- traversalMethod: getNextPosition
- }) {
- while (this.isValidPosition(position)) {
- accumulator = reduceCallback(accumulator, this.getValue(position));
- position = getNextPosition(position);
- }
- return accumulator;
- }
- }
- const toBottomRight = ({ x, y }) => ({ x: x + 1, y: y + 1 });
- const toBottomLeft = ({ x, y }) => ({ x: x - 1, y: y + 1 });
- const sum = (a, b) => a + b;
- function diagonalDifference(arr) {
- const matrix = new Matrix(arr);
- const ltr = matrix.reduce({
- reduceCallback: sum,
- startingPosition: { x: 0, y: 0 },
- traversalMethod: toBottomRight
- });
- const rtl = matrix.reduce({
- reduceCallback: sum,
- startingPosition: { x: matrix.width - 1, y: 0 },
- traversalMethod: toBottomLeft
- });
- return Math.abs(ltr - rtl);
- }
Advertisement
Add Comment
Please, Sign In to add comment