From 22171c07ff67c9de8f4db32dbc3493429826da1e Mon Sep 17 00:00:00 2001 From: newt Date: Wed, 9 Oct 2024 18:02:45 +0100 Subject: [PATCH] feat(euler): 24 - lexographic permutations --- challenges/euler/readme.md | 2 +- .../src/24 - Lexicographic permutations.ts | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 challenges/euler/src/24 - Lexicographic permutations.ts diff --git a/challenges/euler/readme.md b/challenges/euler/readme.md index 882365b..60a1e0f 100644 --- a/challenges/euler/readme.md +++ b/challenges/euler/readme.md @@ -35,7 +35,7 @@ The source code can be found in the [src](src) directory. My thoughts about some - [x] [21 - Amicable numbers](src/21%20-%20Amicable%20numbers.ts) - [x] [22 - Names scores](src/22%20-%20Names%20scores.ts) - [ ] 23 - Non-abundant sums -- [ ] 24 - Lexicographic permutations +- [x] [24 - Lexicographic permutations](src/24%20-%20Lexicographic%20permutations.ts) - [x] [25 - 1000-digit Fibonacci number](src/25%20-%201000-digit%20Fibonacci%20number.ts) - [ ] 26 - Reciprocal cycles - [ ] 27 - Quadratic primes diff --git a/challenges/euler/src/24 - Lexicographic permutations.ts b/challenges/euler/src/24 - Lexicographic permutations.ts new file mode 100644 index 0000000..bb60611 --- /dev/null +++ b/challenges/euler/src/24 - Lexicographic permutations.ts @@ -0,0 +1,40 @@ +// A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: +// 012   021   102   120   201   210 +// What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? +export = {}; + +const getPermutations = (array: T[]) => { + const permutations: T[][] = []; + + if (array.length === 0) return []; + if (array.length === 1) return [array]; + + for (let i = 0; i < array.length; i++) { + const currentValue = array[i]; + const remainingValues = [...array.slice(0, i), ...array.slice(i + 1)]; + const permutedRemains = getPermutations(remainingValues); + + for (let j = 0; j < permutedRemains.length; j++) { + const permutedArray = [currentValue, ...permutedRemains[j]]; + permutations.push(permutedArray); + } + } + + return permutations; +}; + +const orderLexicographically = (permutations: number[][]) => { + return permutations.sort((a, b) => { + const parsedA = parseInt(a.map(v => v.toString()).join('')); + const parsedB = parseInt(b.map(v => v.toString()).join('')); + + return parsedA > parsedB ? 1 : -1; + }); +}; + +const nthLexographicPermutation = (numbers: number[], n: number) => { + const permutations = orderLexicographically(getPermutations(numbers)); + return parseInt(permutations[n - 1].map(v => v.toString()).join('')); +}; + +console.log(nthLexographicPermutation([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1000000));