Project Euler 24: What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
What if repetitions are allowed? like 1111111111,1223344457 etc. How can I get millionth permutation where repetitions are also included in counting.
And please note that input would still be the same. No repetitions in input.
I want to generate all possible passwords of length 10. And passwords can contain repeated characters so I want my function to work for that too.
Here is the code which gives nth permutation of a string. It works by exploiting the fact that for n elements there are n! permutations. And in lexicographic permutation first (n-1)! permutations would start with first digit and so on.
How can I modify this to get strings with repetitions also? Any particular algorithm which I should use?
To clarify things, I don't only need millionth permutation. I need all possible permutations. I can get all permutations without repetitions by running a for loop on this function. But I can't get permutations with repetitions. I want permutations with repetitions. Since I want to get all possible passwords. Think of all the possible passwords that you can have of 10 letters if only numbers were allowed. 10^10. I want all of them.
import java.util.*; public class NthPermutation{ private static int Factorial(int n){ if (n < 0) return 0; int ans = 1; for (int i=1;i<=n;++i) ans *= i; return ans; } public static String getNth(List<Integer> original, int permNum){ List<Integer> numbers = new ArrayList<Integer>(original); String nth = ""; permNum--; int N = numbers.size(); for (int i=1;i<N;++i){ int j = permNum / Factorial(N - i); permNum = permNum % Factorial(N - i); nth = nth + numbers.get(j); numbers.remove(j); if (permNum==0) break; } for (int i=0; i<numbers.size();i++) nth = nth + numbers.get(i); return nth; } public static void main(String[] args){ List<Integer> numbers = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) numbers.add(i); System.out.println(getNth(numbers,1000000)); } }
[1,1,2,3]: permutation # 1 outputs1,1,2,3; permutation # 2 outputs1,1,3,2; permutation # 24 outputs3,2,1,1