Skip to content

Commit e7e5716

Browse files
committed
📦 NEW: Added Solution and Testcases for Project Euler Problem 24
1 parent 31aca33 commit e7e5716

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Project-Euler/Problem024.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function factorial(n) {
2+
return n <= 1 ? 1 : n * factorial(n - 1)
3+
}
4+
5+
export function findNthLexicographicPermutation(digits, n) {
6+
let permutation = ''
7+
let k = n - 1
8+
9+
while (digits.length > 0) {
10+
const fact = factorial(digits.length - 1)
11+
const index = Math.floor(k / fact)
12+
permutation += digits[index]
13+
digits.splice(index, 1)
14+
k %= fact
15+
}
16+
17+
return permutation
18+
}
19+
20+
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
21+
console.log(findNthLexicographicPermutation(digits, 1000000))

Project-Euler/test/Problem024.test.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { describe, it, expect } from 'vitest'
2+
import { findNthLexicographicPermutation } from '../Problem024'
3+
4+
describe('findNthLexicographicPermutation', () => {
5+
it('should return the correct permutation for small cases', () => {
6+
expect(findNthLexicographicPermutation([0, 1, 2], 1)).toBe('012')
7+
expect(findNthLexicographicPermutation([0, 1, 2], 2)).toBe('021')
8+
expect(findNthLexicographicPermutation([0, 1, 2], 6)).toBe('210')
9+
})
10+
11+
it('should return the correct 1st permutation for digits 0-9', () => {
12+
expect(
13+
findNthLexicographicPermutation([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1)
14+
).toBe('0123456789')
15+
})
16+
17+
it('should return the correct millionth permutation for digits 0-9', () => {
18+
expect(
19+
findNthLexicographicPermutation([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1000000)
20+
).toBe('2783915460')
21+
})
22+
23+
it('should return the correct permutation for a smaller set of digits', () => {
24+
expect(findNthLexicographicPermutation([1, 2, 3, 4], 12)).toBe('2431')
25+
expect(findNthLexicographicPermutation([1, 2, 3, 4], 24)).toBe('4321')
26+
})
27+
28+
it('should handle large values of n', () => {
29+
expect(findNthLexicographicPermutation([0, 1, 2, 3, 4], 120)).toBe('43210')
30+
})
31+
})

0 commit comments

Comments
 (0)