|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function matchingCouples(arr) take |
| 3 | + * the arr parameter being passed which will be an array of integers in the |
| 4 | + * following format: [B, G, N] where B represents the number of boys, G |
| 5 | + * represents the number of girls, and N represents how many people you want to |
| 6 | + * pair together. Your program should return the number of different ways you |
| 7 | + * can match boys with girls given the different arguments. For example: if arr |
| 8 | + * is [5, 3, 2], N=2 here so you want to pair together 2 people, so you'll need |
| 9 | + * 1 boy and 1 girl. You have 5 ways to choose a boy and 3 ways to choose a |
| 10 | + * girl, so your program should return 15. Another example: if arr is [10, 5, |
| 11 | + * 4], here N=4 so you need 2 boys and 2 girls. We can choose 2 boys from a |
| 12 | + * possible 10, and we can choose 2 girls from a possible 5. Then we have 2 |
| 13 | + * different ways to pair the chosen boys and girls. Our program should |
| 14 | + * therefore return 900 |
| 15 | + * |
| 16 | + * N will always be an even number and it will never be greater than the maximum |
| 17 | + * of (B, G). B and G will always be greater than zero. |
| 18 | + * |
| 19 | + * https://www.coderbyte.com/results/bhanson:Matching%20Couples:JavaScript |
| 20 | + * |
| 21 | + * @param {array} arr |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +function matchingCouples(arr) { |
| 25 | + const [boys, girls, numPairs] = arr; |
| 26 | + |
| 27 | + const numEachGender = numPairs / 2; |
| 28 | + |
| 29 | + const boyCombos = choose(boys, numEachGender); |
| 30 | + const girlCombos = choose(girls, numEachGender); |
| 31 | + const totalCombos = boyCombos * girlCombos * factorial(numEachGender); |
| 32 | + |
| 33 | + return totalCombos; |
| 34 | +} |
| 35 | + |
| 36 | +function factorial(num) { |
| 37 | + let sum = 1; |
| 38 | + for (let i = 1; i <= num; i++) { |
| 39 | + sum *= i; |
| 40 | + } |
| 41 | + return sum; |
| 42 | +} |
| 43 | + |
| 44 | +function choose(num, k) { |
| 45 | + return factorial(num) / (factorial(k) * factorial(num - k)); |
| 46 | +} |
| 47 | + |
| 48 | +module.exports = matchingCouples; |
0 commit comments