fork download
  1. using System;
  2. using System.Numerics;
  3. using System.Collections.Generic;
  4.  
  5. public static class BigIntExtensions
  6. {
  7. public static BigInteger Factorial(this BigInteger integer)
  8. {
  9. if(integer < 1) return new BigInteger(1);
  10.  
  11. BigInteger result = integer;
  12. for (BigInteger i = 1; i < integer; i++)
  13. {
  14. result = result * i;
  15. }
  16.  
  17. return result;
  18. }
  19. }
  20.  
  21. public class Test
  22. {
  23. public static BigInteger CalcCount(BigInteger n, BigInteger r)
  24. {
  25. BigInteger result = n.Factorial() / (n - r).Factorial();
  26. return result;
  27. }
  28.  
  29. public static int[] nthPerm(BigInteger myIndex, int n, int r, BigInteger total)
  30. {
  31. int j = 0, n1 = n;
  32. BigInteger temp, index1 = myIndex;
  33.  
  34. temp = total ;
  35. List<int> indexList = new List<int>();
  36.  
  37. for (int k = 0; k < n; k++) {
  38. indexList.Add(k);
  39. }
  40.  
  41. int[] res = new int[r];
  42.  
  43. for (int k = 0; k < r; k++, n1--) {
  44. temp /= n1;
  45. j = (int) (index1 / temp);
  46. res[k] = indexList[j];
  47. index1 -= (temp * j);
  48. indexList.RemoveAt(j);
  49. }
  50.  
  51. return res;
  52. }
  53.  
  54. public static void Main()
  55. {
  56. int[] testSet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21};
  57. BigInteger numPerms, n, r;
  58. n = testSet.Length;
  59. r = testSet.Length;
  60. numPerms = CalcCount(n, r);
  61. Console.WriteLine(numPerms);
  62.  
  63. BigInteger testIndex = new BigInteger(1234567890987654321);
  64. int[] myNthIndex = nthPerm(testIndex, (int) n, (int) r, numPerms);
  65. int[] myNthPerm = new int[(int) r];
  66.  
  67. for (int i = 0; i < (int) r; i++) {
  68. myNthPerm[i] = testSet[myNthIndex[i]];
  69. }
  70.  
  71. Console.WriteLine(string.Join(",", myNthPerm));
  72. }
  73. }
Success #stdin #stdout 0.04s 16220KB
stdin
Standard input is empty
stdout
51090942171709440000
1,12,4,18,20,19,7,5,16,11,6,8,21,15,13,2,14,9,10,17,3