Skip to content

Commit 058e0e3

Browse files
committed
permutation.js
1 parent 0995034 commit 058e0e3

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// 20. Calculate nPr (Permutations)
2+
3+
//P(n, r) = n! / (n - r)! for n >= r >= 0
4+
5+
function permutation(n, r) {
6+
if (n < r) return -1;
7+
return factorial(n) / factorial(n - r);
8+
}
9+
10+
function factorial(n) {
11+
return n <= 1 ? 1 : n * factorial(n - 1);
12+
}
13+
14+
console.log(permutation(13, 2));
15+
16+
// using for loop
17+
18+
function permutations(n, r) {
19+
if(n < r) return -1;
20+
21+
let result = n;
22+
23+
for(let i = 1; i < r; i++){
24+
result *= n - i;
25+
}
26+
return result;
27+
}
28+
29+
30+
console.log("4 P 1: ", permutation(4, 1))

0 commit comments

Comments
 (0)