We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Project Euler #24: Lexicographic permutations
Project Euler #24: Lexicographic permutations
Sort by
recency
|
44 Discussions
|
Please Login in order to post a comment
//C# using System; using System.Collections.Generic;
class Program { const int mod = 1000000007;
}
Python Solution
We have 13! possible combinations of the string 'abcdefghijklm'. In it, there are 12! * 13 combinations, each of which has a, b, c, ... m in the beginning. In each of those combinations, there are 11! * 12 combinations, housing the leftover letters.
in python3
def factorial(n): result = 1 for i in range(1, n+1): result *= i return result
def nth_lexicographic_permutation(n, word): n -= 1 # Adjusting for 0-based indexing factorials = [factorial(i) for i in range(len(word))] result = "" available = list(word) for i in range(len(word), 0, -1): index = n // factorials[i-1] n = n % factorials[i-1] result += available.pop(index) return result
word = "abcdefghijklm" for _ in range(int(input().strip()) n = int(input().strip()) result = nth_lexicographic_permutation(n, word) print(result)
JAva code