Skip to content

Commit

Permalink
feat: pyramid algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
francislagares committed Aug 21, 2023
1 parent 84fdfd3 commit 3269e78
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/algorithms/pyramid/pyramid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Option 1
export const pyramid = (n: number) => {
const midpoint = Math.floor((2 * n - 1) / 2);

for (let row = 0; row < n; row++) {
let level = '';

for (let column = 0; column < 2 * n - 1; column++) {
if (midpoint - row <= column && midpoint + row >= column) {
level += '#';
} else {
level += ' ';
}
}

console.log(level);
}
};

// Option 2
export const pyramidWithRecursion = (n: number, row = 0, level = '') => {
if (row === n) {
return;
}

if (level.length === 2 * n - 1) {
console.log(level);
return pyramidWithRecursion(n, row + 1);
}

const midpoint = Math.floor((2 * n - 1) / 2);
let add;
if (midpoint - row <= level.length && midpoint + row >= level.length) {
add = '#';
} else {
add = ' ';
}
pyramidWithRecursion(n, row, level + add);
};
46 changes: 46 additions & 0 deletions src/algorithms/pyramid/tests/pyramid.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { SpyInstance, describe, test, vi } from 'vitest';
import { pyramid, pyramidWithRecursion } from '../pyramid';

describe('Steps Algorithm', () => {
let spy: SpyInstance;

beforeEach(() => {
spy = vi.spyOn(console, 'log').mockImplementation(() => {});
});

afterEach(() => {
spy.mockRestore();
});

test('pyramid is a function', () => {
expect(typeof pyramid).toEqual('function');
expect(typeof pyramidWithRecursion).toEqual('function');
});

test('prints a pryamid for n = 2', () => {
pyramid(2);
pyramidWithRecursion(2);
expect(spy.mock.calls[0][0]).toEqual(' # ');
expect(spy.mock.calls[1][0]).toEqual('###');
expect(spy.mock.calls.length).toEqual(4);
});

test('prints a pryamid for n = 3', () => {
pyramid(3);
pyramidWithRecursion(3);
expect(spy.mock.calls[0][0]).toEqual(' # ');
expect(spy.mock.calls[1][0]).toEqual(' ### ');
expect(spy.mock.calls[2][0]).toEqual('#####');
expect(spy.mock.calls.length).toEqual(6);
});

test('prints a pryamid for n = 4', () => {
pyramid(4);
pyramidWithRecursion(4);
expect(spy.mock.calls[0][0]).toEqual(' # ');
expect(spy.mock.calls[1][0]).toEqual(' ### ');
expect(spy.mock.calls[2][0]).toEqual(' ##### ');
expect(spy.mock.calls[3][0]).toEqual('#######');
expect(spy.mock.calls.length).toEqual(8);
});
});

0 comments on commit 3269e78

Please sign in to comment.