Skip to content

Commit cbb1e36

Browse files
committed
Added hard/bracket_combinations
1 parent 1b7112d commit cbb1e36

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

hard/bracket_combinations.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Have the function bracketCombinations(num) read num which will be an integer
3+
* greater than or equal to zero, and return the number of valid combinations
4+
* that can be formed with num pairs of parentheses. For example, if the input
5+
* is 3, then the possible combinations of 3 pairs of parenthesis, namely:
6+
* ()()(), are ()()(), ()(()), (())(), ((())), and (()()). There are 5 total
7+
* combinations when the input is 3, so your program should return 5.
8+
*
9+
* https://www.coderbyte.com/results/bhanson:Bracket%20Combinations:JavaScript
10+
*
11+
* @param {number} num
12+
* @return {number}
13+
*/
14+
function bracketCombinations(num) {
15+
// https://en.wikipedia.org/wiki/Catalan_number
16+
return (1 / (num + 1)) * choose(2 * num, num);
17+
}
18+
19+
function factorial(num) {
20+
let sum = 1;
21+
for (let i = 1; i <= num; i++) {
22+
sum *= i;
23+
}
24+
return sum;
25+
}
26+
27+
function choose(num, k) {
28+
return factorial(num) / (factorial(k) * factorial(num - k));
29+
}
30+
31+
module.exports = bracketCombinations;

hard/bracket_combinations.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const bracketCombinations = require('./bracket_combinations');
2+
3+
describe('bracketCombinations()', () => {
4+
test('passes Coderbyte.com tests', () => {
5+
expect(bracketCombinations(0)).toBe(1);
6+
7+
expect(bracketCombinations(3)).toBe(5);
8+
9+
expect(bracketCombinations(4)).toBe(14);
10+
11+
expect(bracketCombinations(5)).toBe(42);
12+
13+
expect(bracketCombinations(6)).toBe(132);
14+
15+
expect(bracketCombinations(7)).toBe(429);
16+
17+
expect(bracketCombinations(8)).toBe(1430);
18+
19+
expect(bracketCombinations(9)).toBe(4862);
20+
});
21+
});

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