Skip to content

Commit c5bc1f1

Browse files
authored
Add matrix exercises (#22)
1 parent 6db9c34 commit c5bc1f1

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

src/algorithms/matrices.ts

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* The assumptions is that the matrices are N x M (either square or rectangular)
3+
* The matrices cannot have rows with different sizes.
4+
*/
5+
6+
export function sum(matrix: number[][]): number {
7+
let sum = 0;
8+
9+
for (let i = 0; i < matrix.length; i += 1) {
10+
for (let j = 0; j < matrix[i].length; j += 1) {
11+
sum += matrix[i][j];
12+
}
13+
}
14+
15+
return sum;
16+
}
17+
18+
function getShortestLength(matrix: number[][]): number {
19+
const rows = matrix.length;
20+
const columns = matrix[0].length;
21+
22+
if (rows < columns) return rows;
23+
24+
return columns;
25+
}
26+
27+
export function sumDiagonal(matrix: number[][]): number {
28+
let sum = 0;
29+
let index = 0;
30+
31+
const shortestLength = getShortestLength(matrix);
32+
33+
while (index < shortestLength) {
34+
sum += matrix[index][index];
35+
index += 1;
36+
}
37+
38+
return sum;
39+
}
40+
41+
export function sumAntiDiagonal(matrix: number[][]): number {
42+
let sum = 0;
43+
let index = 0;
44+
45+
const shortestLength = getShortestLength(matrix);
46+
47+
while (index < shortestLength) {
48+
sum += matrix[index][matrix.length - 1 - index];
49+
index += 1;
50+
}
51+
52+
return sum;
53+
}
54+
55+
export function sumFrame(matrix: number[][]): number {
56+
let sum = 0;
57+
58+
const numberOfRows = matrix.length;
59+
const numberOfColumns = matrix[0].length; // assuming every row has the same size
60+
61+
// scann horizontally: top + bottom
62+
for (let index = 0; index < numberOfColumns; index += 1) {
63+
sum += matrix[0][index] + matrix[numberOfRows - 1][index];
64+
}
65+
66+
// scan vertically: left + right
67+
for (let index = 1; index < numberOfRows - 1; index += 1) {
68+
sum += matrix[index][0] + matrix[index][numberOfColumns - 1];
69+
}
70+
71+
return sum;
72+
}

test/algorithms/matrices.test.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { sum, sumDiagonal, sumAntiDiagonal, sumFrame } from 'src/algorithms/matrices';
2+
3+
const matrix = [
4+
[7, 3, 1, 0],
5+
[9, 6, 4, 5],
6+
[1, 9, 5, 4],
7+
[6, 8, 2, 3],
8+
];
9+
10+
test('sum', () => {
11+
expect(sum(matrix)).toBe(73);
12+
});
13+
14+
test('sumDiagonal', () => {
15+
expect(sumDiagonal(matrix)).toBe(21);
16+
});
17+
18+
test('sumAntiDiagonal', () => {
19+
expect(sumAntiDiagonal(matrix)).toBe(19);
20+
});
21+
22+
test('sumFrame', () => {
23+
expect(sumFrame(matrix)).toBe(49);
24+
});

0 commit comments

Comments
 (0)