Решение линейного уравнения методом Крамера - C#

Узнай цену своей работы

Формулировка задачи:

помогите решить линейное уравнение методом Крамера х1+2х2-3х3= 3х2-х3= 2х1-х2+2х3= если х1=2, х2=0, х3=2

Решение задачи: «Решение линейного уравнения методом Крамера»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace CramersEquations
  8. {
  9.     class Calculator
  10.     {
  11.         private int numberOfEquations;
  12.         private char[] indeterminates;
  13.         private List<string> equations;
  14.  
  15.         public Calculator()
  16.         {
  17.             SetNumberOfEquations(3);
  18.             CreateIndeterminatesNames();
  19.             InitializeEquations();
  20.         }
  21.  
  22.         public int GetNumberOfEquations()
  23.         {
  24.             return numberOfEquations;
  25.         }
  26.  
  27.         public void SetNumberOfEquations(int number)
  28.         {
  29.             if (number != 3)
  30.             {
  31.                 throw new NotImplementedException();
  32.             }
  33.  
  34.             numberOfEquations = number;
  35.         }
  36.  
  37.         private void CreateIndeterminatesNames()
  38.         {
  39.             indeterminates = new char[] { 'x', 'y', 'z' };
  40.         }
  41.  
  42.         private void CalculateMatrxDeterminant(int dimension)
  43.         {
  44.             // To implement thae function you can use Chio's method (more info: [url]https://www.youtube.com/watch?v=_JetUVpvFAU[/url])
  45.         }
  46.  
  47.         /// <summary>
  48.         /// Temporary function replacing the generic one above
  49.         /// </summary>
  50.         private float Calculate3x3MatrixDeterminant(float[] matrix)
  51.         {
  52.             // Here I use single dimensional array for the matrix:
  53.             // [0][1][2]
  54.             // [3][4][5]
  55.             // [6][7][8]
  56.  
  57.             if (matrix.Count() != 9)
  58.             {
  59.                 throw new IndexOutOfRangeException();
  60.             }
  61.  
  62.             float first = matrix[4] * matrix[8] - matrix[5] * matrix[7];
  63.             float second = matrix[3] * matrix[8] - matrix[5] * matrix[6];
  64.             float third = matrix[3] * matrix[7] - matrix[4] * matrix[6];
  65.  
  66.             return matrix[0] * first - matrix[1] * second + matrix[2] * third;
  67.         }
  68.  
  69.         public static string[] GetReadMeContent()
  70.         {
  71.             return new string[]
  72.             {
  73.                 "Greetings, friend!",
  74.                 "I am a little program calculating the very simple system of equations (3 only yet).",
  75.                 "You will be prompted to enter the equations by the following scheme: ax+by+cz=d",
  76.                 "'x', 'y', 'z' characters represent indeterminates and all should be contained within the equation.",
  77.                 "Indeterminates should be contained within the equation only once and only on the left side of the equal sign",
  78.                 "Equal sign must be followed by the number only",
  79.                 "'a', 'b', 'c' and 'd' characters must be replaced with integer numbers with '+' or '-' sign in front of it only",
  80.                 "For example: 2x-5y+0.3z=25",
  81.                 "'a', 'b', 'c' or 'd' cannot be zeros, since they collapse the variable.",
  82.                 "Numbers with fraction or functions are not allowed either.",
  83.                 "You can use spaces within the equation."
  84.             };
  85.         }
  86.  
  87.         public Tuple<string, bool> TryAddEquation(string equation)
  88.         {
  89.             if (equation.Count(c => c == '=') != 1)
  90.             {
  91.                 return Tuple.Create("Equal sign should be appearing in the equation only once!", false);
  92.             }
  93.  
  94.             int result;
  95.             if (!int.TryParse(equation.Split('=').Last(), out result))
  96.             {
  97.                 return Tuple.Create("An integer number only must be followed by the '='", false);
  98.             }
  99.  
  100.             foreach(char indeterminate in indeterminates)
  101.             {
  102.                 if (equation.Count(c => c == indeterminate) != 1)
  103.                 {
  104.                     return Tuple.Create("The " + indeterminate.ToString() + " must be appearing in the equationonly once!", false);
  105.                 }
  106.             }
  107.  
  108.             if (equation.Count(c => c == '*') > 0)
  109.             {
  110.                 return Tuple.Create("Cannot use multiplication here yet", false);
  111.             }
  112.  
  113.             if (equation.Count(c => c == '/') > 0)
  114.             {
  115.                 return Tuple.Create("Cannot use division here yet", false);
  116.             }
  117.  
  118.             // Add other tests to make sure the equations follows the rules:
  119.             // 1). Make sure other characters not used
  120.             // 2). Make sure equations are not the same
  121.             // 3). Make sure variables follow the order (x first, y next and z last) or do the mapping when calculating results
  122.             // 4). Consider some other validations maybe?
  123.  
  124.             equations.Add(equation.Replace(" ", "").Replace("+", ""));
  125.  
  126.             return Tuple.Create("Equation was successfully read.", true);
  127.         }
  128.  
  129.         public void InitializeEquations()
  130.         {
  131.             equations = new List<string>();
  132.         }
  133.  
  134.         /// <summary>
  135.         /// Remember, it works only on 3x3 matrices for now
  136.         /// </summary>
  137.         public string[] CalculateResults()
  138.         {
  139.             /*equations.Add("2x+5y+4z=30");
  140.             equations.Add("x+3y+2z=150");
  141.             equations.Add("2x+10y+9z=110");*/
  142.  
  143.             if (!equations.Any())
  144.             {
  145.                 throw new ArgumentOutOfRangeException();
  146.             }
  147.  
  148.             var matrix = PopulateMatrix();
  149.  
  150.             var det = Generate3x3MatrixFrom3x4Matrix(matrix, new int[] { 0, 1, 2, 4, 5, 6, 8, 9, 10 });
  151.             float[] determinants = new float[indeterminates.Length];
  152.             determinants[0] = Generate3x3MatrixFrom3x4Matrix(matrix, new int[] { 3, 1, 2, 7, 5, 6, 11, 9, 10 });
  153.             determinants[1] = Generate3x3MatrixFrom3x4Matrix(matrix, new int[] { 0, 3, 2, 4, 7, 6, 8, 11, 10 });
  154.             determinants[2] = Generate3x3MatrixFrom3x4Matrix(matrix, new int[] { 0, 1, 3, 4, 5, 7, 8, 9, 11 });
  155.            
  156.             string[] results = new string[indeterminates.Length];
  157.  
  158.             for (int i = 0; i < indeterminates.Length; i++)
  159.             {
  160.                 float result = determinants[i] / det;
  161.                 results[i] = indeterminates[i].ToString() + " = " + result.ToString();
  162.             }
  163.  
  164.             return results;
  165.         }
  166.  
  167.         private float Generate3x3MatrixFrom3x4Matrix(float[] matrix3x4, int[] indices)
  168.         {
  169.             int count = indeterminates.Count();
  170.             int initialSize = count * (count + 1);
  171.             int targetSize = count * count;
  172.  
  173.             if (matrix3x4.Length != initialSize)
  174.             {
  175.                 throw new IndexOutOfRangeException();
  176.             }
  177.  
  178.             if (indices.Length != targetSize)
  179.             {
  180.                 throw new IndexOutOfRangeException();
  181.             }
  182.  
  183.             float[] matrix = new float[targetSize];
  184.             for (int i = 0; i < targetSize; i++)
  185.             {
  186.                 matrix[i] = matrix3x4[indices[i]];
  187.             }
  188.  
  189.             return Calculate3x3MatrixDeterminant(matrix);
  190.         }
  191.  
  192.         private float[] PopulateMatrix()
  193.         {
  194.             StringBuilder builder = new StringBuilder();
  195.             int index = 0;
  196.             int numberOfIndeterminates = indeterminates.Count();
  197.             int matrixSize = numberOfIndeterminates * (numberOfIndeterminates + 1);
  198.             float[] matrix = new float[matrixSize];
  199.  
  200.             foreach (string equation in equations)
  201.             {
  202.                 var parts = equation.Split('=');
  203.                 string firstPart = parts[0];
  204.                 var coefficients = firstPart.Split(indeterminates).ToList();
  205.                 coefficients[coefficients.Count - 1] = parts[1];
  206.  
  207.                 for (int i = 0; i < coefficients.Count; i++)
  208.                 {
  209.                     if (coefficients[i] == string.Empty)
  210.                     {
  211.                         coefficients[i] = "1";
  212.                     }
  213.                     else if (coefficients[i] == "-")
  214.                     {
  215.                         coefficients[i] = "-1";
  216.                     }
  217.  
  218.                     matrix[index] = float.Parse(coefficients[i]);
  219.                     index++;
  220.                 }
  221.             }
  222.  
  223.             return matrix;
  224.         }
  225.     }
  226. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

12   голосов , оценка 3.917 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы