Skip to content

Commit 37bcd2b

Browse files
committed
Add the 'rotate matrix' algorithm
1 parent 8064f53 commit 37bcd2b

File tree

4 files changed

+42
-0
lines changed

4 files changed

+42
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ An algorithm is a finite sequence of well-defined, computer-implementable instru
3131
* [Check permutation](src/algorithms/string/permutation) - check if a string is a permutation of the other;
3232
* [URLify](src/algorithms/string/urlify) - replace all spaces in a string with '%20';
3333
* [String compression](src/algorithms/string/compression) - perform basic string compression using the counts of repeated characters;
34+
* [Rotate matrix](src/algorithms/string/rotate-matrix) - rotate the matrix by 90 degrees;
3435
* **Sort**
3536
* [Insertion sort](src/algorithms/sort/insertion/simple) - sort an array with a simple insertion algorithm;
3637
* [Merge sort](src/algorithms/sort/merge) - sort an array with a merge sort algorithm;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Rotate Matrix
2+
3+
Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
4+
5+
References:
6+
* https://math.stackexchange.com/questions/1676441/how-to-rotate-the-positions-of-a-matrix-by-90-degrees
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { rotateMatrix } from "../rotateMatrix";
2+
3+
test("rotate matrix is successful", () => {
4+
const input = [
5+
[1, 1, 1],
6+
[2, 2, 2],
7+
[3, 3, 3],
8+
];
9+
10+
const expected = [
11+
[3, 2, 1],
12+
[3, 2, 1],
13+
[3, 2, 1],
14+
];
15+
debugger;
16+
expect(rotateMatrix(input)).toStrictEqual(expected);
17+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* Rotate the matrix by 90 degrees
3+
* @param {number[][]} matrix
4+
* @returns number
5+
*/
6+
export function rotateMatrix(matrix: number[][]): number[][] {
7+
const output = JSON.parse(JSON.stringify(matrix));
8+
9+
const len = output.length - 1;
10+
11+
for (let i = 0; i < output.length; i++) {
12+
for (let j = 0; j < output.length; j++) {
13+
output[j][len - i] = matrix[i][j];
14+
}
15+
}
16+
17+
return output;
18+
}

0 commit comments

Comments
 (0)