fork(57) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. static public void findPermutation(int n, int k)
  11. {
  12. int[] numbers = new int[n];
  13. int[] indices = new int[n];
  14.  
  15. // initialise the numbers 1, 2, 3...
  16. for (int i = 0; i < n; i++)
  17. numbers[i] = i + 1;
  18.  
  19. int divisor = 1;
  20. for (int place = 1; place <= n; place++)
  21. {
  22. if((k / divisor) == 0)
  23. break; // all the remaining indices will be zero
  24.  
  25. // compute the index at that place:
  26. indices[n-place] = (k / divisor) % place;
  27. divisor *= place;
  28. }
  29.  
  30. // print out the indices:
  31. // System.out.println(Arrays.toString(indices));
  32.  
  33. // permute the numbers array according to the indices:
  34. for (int i = 0; i < n; i++)
  35. {
  36. int index = indices[i] + i;
  37.  
  38. // take the element at index and place it at i, moving the rest up
  39. if(index != i)
  40. {
  41. int temp = numbers[index];
  42. for(int j = index; j > i; j--)
  43. numbers[j] = numbers[j-1];
  44. numbers[i] = temp;
  45. }
  46. }
  47.  
  48. System.out.println(Arrays.toString(numbers));
  49. }
  50.  
  51. public static void main (String[] args) throws java.lang.Exception
  52. {
  53. // your code goes here
  54. for(int i = 0; i < 6; i++)
  55. findPermutation(3, i);
  56.  
  57. findPermutation(100, 10000000-1);
  58. }
  59. }
Success #stdin #stdout 0.1s 320320KB
stdin
Standard input is empty
stdout
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 92, 98, 96, 90, 91, 100, 94, 97, 95, 99, 93]