|
1 | 1 | export function countUniqueSongs(birds: Array<string>): number { |
2 | 2 | if (!birds || birds.length === 0) return 0; |
3 | | - if (birds.length === 1) { |
4 | | - const birdCombos = [['A']]; // 1 bird |
5 | | - const branchCombos = [['1'], ['2'], ['3']]; // each possible branch |
6 | | - return birdCombos.length * branchCombos.length; // 1 * 3 = 3 |
7 | | - } |
8 | | - if (birds.length === 2) { |
9 | | - const birdCombos = [ |
10 | | - ['A', 'B'], |
11 | | - ['A', 'C'], |
12 | | - ['B', 'C'], |
13 | | - ]; |
14 | | - const branchCombos = [ |
15 | | - ['1', '2'], |
16 | | - ['1', '3'], |
17 | | - ['2', '3'], |
18 | | - ]; |
19 | | - return birdCombos.length * branchCombos.length * factorial(2); |
20 | | - } |
21 | | - if (birds.length === 3) { |
22 | | - const permutationsOfBirds = [ |
23 | | - ['A', 'B', 'C'], |
24 | | - ['A', 'C', 'B'], |
25 | | - ['B', 'A', 'C'], |
26 | | - ['B', 'C', 'A'], |
27 | | - ['C', 'A', 'B'], |
28 | | - ['C', 'B', 'A'], |
29 | | - ]; |
30 | | - const permutationsOfBranches = [ |
31 | | - ['1', '2', '3'], |
32 | | - ['1', '3', '2'], |
33 | | - ['2', '1', '3'], |
34 | | - ['2', '3', '1'], |
35 | | - ['3', '1', '2'], |
36 | | - ['3', '2', '1'], |
37 | | - ]; |
38 | | - return permutationsOfBirds.length * permutationsOfBranches.length; |
39 | | - } |
| 3 | + |
| 4 | + const BRANCH_COUNT = 3; |
| 5 | + const birdCount = birds.length; |
| 6 | + |
| 7 | + const songCalculator = { |
| 8 | + 1: () => BRANCH_COUNT, // One bird can perch on any of the 3 branches |
| 9 | + 2: () => { |
| 10 | + const birdCombinations = 3; // Number of ways to choose 2 birds from the set |
| 11 | + const branchCombinations = 3; // Number of ways to choose 2 branches from 3 |
| 12 | + const birdPermutations = factorial(2); // Number of ways to arrange 2 birds |
| 13 | + return birdCombinations * branchCombinations * birdPermutations; // 3 * 3 * 2 = 18 |
| 14 | + }, |
| 15 | + 3: () => { |
| 16 | + const birdPermutations = factorial(3); // Number of ways to arrange 3 birds |
| 17 | + const branchPermutations = factorial(3); // Number of ways to arrange 3 branches |
| 18 | + return birdPermutations * branchPermutations; // 6 * 6 = 36 |
| 19 | + }, |
| 20 | + }; |
| 21 | + |
| 22 | + return songCalculator[birdCount] ? songCalculator[birdCount]() : 0; |
40 | 23 | } |
41 | 24 |
|
42 | 25 | function factorial(n: number): number { |
|
0 commit comments