fork download
  1. using System;
  2. using System.CodeDom;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace ConsoleApplication4
  9. {
  10. class Program
  11. {
  12. private static void Main(string[] args)
  13. { var m = new int[,]
  14. {
  15. {1, 2, 3, 4},
  16. {2, 1, 1, 1},
  17. {3, 1, 2, 1},
  18. {4, 1, 1, 1},
  19. };
  20.  
  21. Console.WriteLine(GetDeterminant(m));
  22.  
  23. m = new int[,]
  24. {
  25. {1, 2, 3, 4,5,1, 2, 3, 4,5,},
  26. {2, 1, 1, 1,3,1, 2, 3, 4,5,},
  27. {3, 1, 2, 1,8,1, 2, 3, 4,5,},
  28. {4, 1, 1, 1,1,1, 2, 3, 4,5,},
  29. {4, 10, 1, 2,1,1, 2, 3, 4,5,},
  30. {1, 2, 3, 4,5,1, 2, 3, 4,5,},
  31. {2, 1, 1, 1,3,1, 2, 3, 4,5,},
  32. {3, 1, 2, 1,8,1, 2, 3, 4,5,},
  33. {4, 1, 1, 1,1,1, 2, 3, 4,5,},
  34. {4, 10, 1, 2,1,1, 2, 3, 4,5,},
  35. };
  36.  
  37. Console.WriteLine(GetDeterminant(m));
  38.  
  39.  
  40. }
  41.  
  42.  
  43. private static void NextPermutation(int[] permutation, ref bool isPositive)
  44. {
  45. int lenght = permutation.Length, firstIndex = 0, secondIndex;
  46.  
  47. for (int i = 0; i < lenght - 1; i++)
  48. if (permutation[i] < permutation[i + 1])
  49. firstIndex = i;
  50.  
  51. secondIndex = lenght-1;
  52.  
  53. while (permutation[firstIndex] > permutation[secondIndex])
  54. secondIndex--;
  55.  
  56. swapInArray(permutation, firstIndex, secondIndex);
  57. var count = (lenght - firstIndex-1) / 2;
  58.  
  59. for (int i = 1; i <= count; i++)
  60. swapInArray(permutation, firstIndex + i, lenght - i);
  61.  
  62. if (count%2 == 0) isPositive = !isPositive;
  63. }
  64.  
  65. private static void swapInArray(int[] array, int firstIndex, int secondIndex)
  66. {
  67. var temp = array[firstIndex];
  68. array[firstIndex] = array[secondIndex];
  69. array[secondIndex] = temp;
  70. }
  71.  
  72. static int GetDeterminant(int[,] matrix)
  73. {
  74. var rang = matrix.GetLength(0);
  75. if(rang != matrix.GetLength(1)) // fatal error
  76. throw new Exception("Bad matrix");
  77. if (rang == 1) return matrix[0, 0];
  78.  
  79. var indexes = new int[rang];
  80.  
  81. var countOfPermutation = 1;
  82.  
  83. for (int i = 0; i < rang; i++)
  84. {
  85. indexes[i] = i;
  86. countOfPermutation *= (i + 1);
  87. }
  88.  
  89. int determinant = 0, multiplication;
  90. bool isPositive = true;
  91.  
  92. for (int i = 0; i < countOfPermutation; i++)
  93. {
  94. multiplication = 1;
  95. for (int j = 0; j < rang; j++)
  96. multiplication *= matrix[j, indexes[j]];
  97.  
  98. determinant += multiplication * (isPositive?1:-1);
  99.  
  100. NextPermutation(indexes,ref isPositive);
  101. }
  102.  
  103. return determinant;
  104. }
  105. }
  106. }
  107.  
Success #stdin #stdout 0.9s 23952KB
stdin
Standard input is empty
stdout
-4
0