@@ -0,0 +1,192 @@
3+namespace SolveAvdoshin
5+ public class SystemNonConsistentException : Exception
10+ public class AndXorEquation
12+ public static int[] ConvertToBinary(int n)
14+ int[] result = new int[(int)Math.Log(n, 2) + 1];
18+ result[lastIndex++] = n % 2;
25+ public static int SolveEq(int[] coefs)
27+ if(coefs.Length != 9)
28+ throw new ArgumentException("Input array shold be 9 elements long");
30+ int[,] binaryCoefs = new int[8, 9];
32+ for(int i = 0; i <= 8; i++) {
33+ int[] binary = ConvertToBinary(coefs[i]);
35+ for(int j = 0; j < binary.Length; j++) {
36+ binaryCoefs[7 - j, i] = binary[j];
40+ var matrix = new AndXorSystem(binaryCoefs);
43+ return matrix.Solve();
45+ catch(SystemNonConsistentException) {
51+ public class AndXorSystem
56+ public AndXorSystem(int[,] matrix)
58+ if(matrix.GetLength(0) + 1 != matrix.GetLength(1))
59+ throw new ArgumentException("The array supplied isn't an Nx(N+1) matrix");
61+ NumRows = matrix.GetLength(0);
63+ for(int i = 0; i < NumRows; i++) {
64+ for(int j = 0; j < NumRows + 1; j++) {
65+ if(matrix[i, j] != 0 && matrix[i, j] != 1)
66+ throw new ArgumentException("The array supplied contains non-binary elements");
73+ public override string ToString()
77+ for(int i = 0; i < NumRows; i++) {
80+ for(int j = 0; j < NumRows + 1; j++) {
81+ result += Matrix[i, j].ToString("D") + (j == 7 ? " | " : " ");
90+ void SwapRows(int a, int b)
92+ if(a < 0 || a >= NumRows || b < 0 || b >= NumRows)
93+ throw new ArgumentOutOfRangeException();
95+ for(int i = 0; i < NumRows + 1; i++) {
96+ int t = Matrix[a, i];
97+ Matrix[a, i] = Matrix[b, i];
102+ void XorRowIntoAnother(int a, int b)
104+ if(a < 0 || a >= NumRows || b < 0 || b >= NumRows)
105+ throw new ArgumentOutOfRangeException();
107+ for(int i = 0; i < NumRows + 1; i++) {
108+ Matrix[b, i] ^= Matrix[a, i];
112+ void MakeCanonical()
114+ // Реализуется алгоритм Гаусса, как Чернышев завещал
116+ int curRow = 0, curCol = 0;
118+ while(curRow < NumRows && curCol < NumRows) {
119+ if(Matrix[curRow, curCol] != 0) {
120+ for(int i = 0; i < NumRows; i++) {
124+ if(Matrix[i, curCol] == 1) {
125+ XorRowIntoAnother(curRow, i);
133+ int nonZeroRow = curRow;
135+ for(int i = curRow + 1; i < NumRows; i++) {
136+ if(Matrix[i, curCol] != 0) {
142+ if(nonZeroRow != curRow) {
143+ SwapRows(curRow, nonZeroRow);
156+ bool CheckConsistency()
158+ for(int i = 0; i < NumRows; i++) {
159+ bool nonZeroRow = false;
161+ for(int j = 0; j < NumRows; j++) {
162+ if(Matrix[i, j] != 0) {
168+ if(!nonZeroRow && (Matrix[i, 8] != 0))
179+ if(!CheckConsistency())
180+ throw new SystemNonConsistentException();
182+ int result = 0, power = 1;
183+ for(int i = 0; i < 8; i++) {
184+ result += Matrix[7 - i, 8] * power;