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

Dynamic-Programming/CatalanNumbers.js

Lines changed: 30 additions & 0 deletions
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+
}
Lines changed: 14 additions & 0 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy