mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
algorithm: catalan numbers (#1149)
This commit is contained in:
30
Dynamic-Programming/CatalanNumbers.js
Normal file
30
Dynamic-Programming/CatalanNumbers.js
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
/*
|
||||||
|
* Author: IcarusTheFly (https://github.com/IcarusTheFly)
|
||||||
|
* Catalan Numbers explanation can be found in the following links:
|
||||||
|
* Wikipedia: https://en.wikipedia.org/wiki/Catalan_number
|
||||||
|
* Brilliant: https://brilliant.org/wiki/catalan-numbers
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @function catalanNumbers
|
||||||
|
* @description Returns all catalan numbers from index 0 to n
|
||||||
|
* @param {number} n
|
||||||
|
* @returns {number[]} Array with the catalan numbers from 0 to n
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const catalanNumbers = (n) => {
|
||||||
|
if (n === 0) {
|
||||||
|
return [1]
|
||||||
|
}
|
||||||
|
const catList = [1, 1]
|
||||||
|
|
||||||
|
for (let i = 2; i <= n; i++) {
|
||||||
|
let newNumber = 0
|
||||||
|
for (let j = 0; j < i; j++) {
|
||||||
|
newNumber += catList[j] * catList[i - j - 1]
|
||||||
|
}
|
||||||
|
catList.push(newNumber)
|
||||||
|
}
|
||||||
|
|
||||||
|
return catList
|
||||||
|
}
|
14
Dynamic-Programming/tests/CatalanNumbers.test.js
Normal file
14
Dynamic-Programming/tests/CatalanNumbers.test.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { catalanNumbers } from '../CatalanNumbers'
|
||||||
|
|
||||||
|
describe('Testing catalanNumbers function', () => {
|
||||||
|
test('should return the expected array for inputs from 0 to 20', () => {
|
||||||
|
const expectedOutput = [
|
||||||
|
1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900,
|
||||||
|
2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420
|
||||||
|
]
|
||||||
|
|
||||||
|
for (let i = 0; i <= 20; i++) {
|
||||||
|
expect(catalanNumbers(i)).toStrictEqual(expectedOutput.slice(0, i + 1))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
Reference in New Issue
Block a user