Skip to content

Commit 3269e78

Browse files
feat: pyramid algorithm
1 parent 84fdfd3 commit 3269e78

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

src/algorithms/pyramid/pyramid.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Option 1
2+
export const pyramid = (n: number) => {
3+
const midpoint = Math.floor((2 * n - 1) / 2);
4+
5+
for (let row = 0; row < n; row++) {
6+
let level = '';
7+
8+
for (let column = 0; column < 2 * n - 1; column++) {
9+
if (midpoint - row <= column && midpoint + row >= column) {
10+
level += '#';
11+
} else {
12+
level += ' ';
13+
}
14+
}
15+
16+
console.log(level);
17+
}
18+
};
19+
20+
// Option 2
21+
export const pyramidWithRecursion = (n: number, row = 0, level = '') => {
22+
if (row === n) {
23+
return;
24+
}
25+
26+
if (level.length === 2 * n - 1) {
27+
console.log(level);
28+
return pyramidWithRecursion(n, row + 1);
29+
}
30+
31+
const midpoint = Math.floor((2 * n - 1) / 2);
32+
let add;
33+
if (midpoint - row <= level.length && midpoint + row >= level.length) {
34+
add = '#';
35+
} else {
36+
add = ' ';
37+
}
38+
pyramidWithRecursion(n, row, level + add);
39+
};
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { SpyInstance, describe, test, vi } from 'vitest';
2+
import { pyramid, pyramidWithRecursion } from '../pyramid';
3+
4+
describe('Steps Algorithm', () => {
5+
let spy: SpyInstance;
6+
7+
beforeEach(() => {
8+
spy = vi.spyOn(console, 'log').mockImplementation(() => {});
9+
});
10+
11+
afterEach(() => {
12+
spy.mockRestore();
13+
});
14+
15+
test('pyramid is a function', () => {
16+
expect(typeof pyramid).toEqual('function');
17+
expect(typeof pyramidWithRecursion).toEqual('function');
18+
});
19+
20+
test('prints a pryamid for n = 2', () => {
21+
pyramid(2);
22+
pyramidWithRecursion(2);
23+
expect(spy.mock.calls[0][0]).toEqual(' # ');
24+
expect(spy.mock.calls[1][0]).toEqual('###');
25+
expect(spy.mock.calls.length).toEqual(4);
26+
});
27+
28+
test('prints a pryamid for n = 3', () => {
29+
pyramid(3);
30+
pyramidWithRecursion(3);
31+
expect(spy.mock.calls[0][0]).toEqual(' # ');
32+
expect(spy.mock.calls[1][0]).toEqual(' ### ');
33+
expect(spy.mock.calls[2][0]).toEqual('#####');
34+
expect(spy.mock.calls.length).toEqual(6);
35+
});
36+
37+
test('prints a pryamid for n = 4', () => {
38+
pyramid(4);
39+
pyramidWithRecursion(4);
40+
expect(spy.mock.calls[0][0]).toEqual(' # ');
41+
expect(spy.mock.calls[1][0]).toEqual(' ### ');
42+
expect(spy.mock.calls[2][0]).toEqual(' ##### ');
43+
expect(spy.mock.calls[3][0]).toEqual('#######');
44+
expect(spy.mock.calls.length).toEqual(8);
45+
});
46+
});

0 commit comments

Comments
 (0)