Skip to content

Commit ede60b8

Browse files
authored
algorithm: catalan numbers (#1149)
1 parent 78f023f commit ede60b8

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Diff for: Dynamic-Programming/CatalanNumbers.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
* Author: IcarusTheFly (https://github.com/IcarusTheFly)
3+
* Catalan Numbers explanation can be found in the following links:
4+
* Wikipedia: https://en.wikipedia.org/wiki/Catalan_number
5+
* Brilliant: https://brilliant.org/wiki/catalan-numbers
6+
*/
7+
8+
/**
9+
* @function catalanNumbers
10+
* @description Returns all catalan numbers from index 0 to n
11+
* @param {number} n
12+
* @returns {number[]} Array with the catalan numbers from 0 to n
13+
*/
14+
15+
export const catalanNumbers = (n) => {
16+
if (n === 0) {
17+
return [1]
18+
}
19+
const catList = [1, 1]
20+
21+
for (let i = 2; i <= n; i++) {
22+
let newNumber = 0
23+
for (let j = 0; j < i; j++) {
24+
newNumber += catList[j] * catList[i - j - 1]
25+
}
26+
catList.push(newNumber)
27+
}
28+
29+
return catList
30+
}

Diff for: Dynamic-Programming/tests/CatalanNumbers.test.js

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { catalanNumbers } from '../CatalanNumbers'
2+
3+
describe('Testing catalanNumbers function', () => {
4+
test('should return the expected array for inputs from 0 to 20', () => {
5+
const expectedOutput = [
6+
1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900,
7+
2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420
8+
]
9+
10+
for (let i = 0; i <= 20; i++) {
11+
expect(catalanNumbers(i)).toStrictEqual(expectedOutput.slice(0, i + 1))
12+
}
13+
})
14+
})

0 commit comments

Comments
 (0)