Skip to content

Add matrix exercises #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions src/algorithms/matrices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* The assumptions is that the matrices are N x M (either square or rectangular)
* The matrices cannot have rows with different sizes.
*/

export function sum(matrix: number[][]): number {
let sum = 0;

for (let i = 0; i < matrix.length; i += 1) {
for (let j = 0; j < matrix[i].length; j += 1) {
sum += matrix[i][j];
}
}

return sum;
}

function getShortestLength(matrix: number[][]): number {
const rows = matrix.length;
const columns = matrix[0].length;

if (rows < columns) return rows;

return columns;
}

export function sumDiagonal(matrix: number[][]): number {
let sum = 0;
let index = 0;

const shortestLength = getShortestLength(matrix);

while (index < shortestLength) {
sum += matrix[index][index];
index += 1;
}

return sum;
}

export function sumAntiDiagonal(matrix: number[][]): number {
let sum = 0;
let index = 0;

const shortestLength = getShortestLength(matrix);

while (index < shortestLength) {
sum += matrix[index][matrix.length - 1 - index];
index += 1;
}

return sum;
}

export function sumFrame(matrix: number[][]): number {
let sum = 0;

const numberOfRows = matrix.length;
const numberOfColumns = matrix[0].length; // assuming every row has the same size

// scann horizontally: top + bottom
for (let index = 0; index < numberOfColumns; index += 1) {
sum += matrix[0][index] + matrix[numberOfRows - 1][index];
}

// scan vertically: left + right
for (let index = 1; index < numberOfRows - 1; index += 1) {
sum += matrix[index][0] + matrix[index][numberOfColumns - 1];
}

return sum;
}
24 changes: 24 additions & 0 deletions test/algorithms/matrices.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { sum, sumDiagonal, sumAntiDiagonal, sumFrame } from 'src/algorithms/matrices';

const matrix = [
[7, 3, 1, 0],
[9, 6, 4, 5],
[1, 9, 5, 4],
[6, 8, 2, 3],
];

test('sum', () => {
expect(sum(matrix)).toBe(73);
});

test('sumDiagonal', () => {
expect(sumDiagonal(matrix)).toBe(21);
});

test('sumAntiDiagonal', () => {
expect(sumAntiDiagonal(matrix)).toBe(19);
});

test('sumFrame', () => {
expect(sumFrame(matrix)).toBe(49);
});