How to use permutation formula In Javascript
- Permutations Formula: Apply the formula P(n, r) = n! / (n – r)! to find permutations efficiently.
- Iterative Factorial: Optimize factorial computation using an iterative approach for ‘n’ and ‘n – r’.
- JavaScript Implementation: Develop a function using loops to compute factorial and calculate permutations.
- Performance Evaluation: Assess the performance gains compared to recursive factorial calculation, especially for larger ‘n’ and ‘r’ values.
Example: The below code uses the permutation formula to calculate the permutations in which n people can occupy r seats.
function calculateFactorial(num) {
if (num === 0 || num === 1) {
return 1;
} else {
return num *
calculateFactorial(num - 1);
}
}
function calculatePermutations(n, r) {
return calculateFactorial(n) /
calculateFactorial(n - r);
}
const n = 5;
const r = 3;
const totalArrangements =
calculatePermutations(n, r);
console.log(
`Total arrangements: ${totalArrangements}`);
Output
Total arrangements: 60
Time complexity: O(n),
Space complexity: O(n)
Permutations in which n People can Occupy r Seats in a Classroom using JavaScript
In this article, we’ll explore how to calculate permutations in JavaScript, specifically focusing on scenarios where ‘n’ people need to occupy ‘r’ seats in a classroom. Permutations, which determine the number of ways people can be arranged, are essential in various settings like event planning.
Examples:
Input: n = 5, r = 3
Output: 60
Explanation: 5 people can sit on 3 seats in 60 ways.
Input: n = 6, r = 4
Output: 360
Explanation: 6 people can sit on 4 seats in 360 ways.
Table of Content
- Using permutation formula
- By optimizing the permutation formula