Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* тз:
- Реализовать класс квадратной матрицы произвольного размера и для него
- операции сложения, умножения, деления, нахождение определителя и транспонирования. При
- невозможности выполнить какую-либо операцию генерируйте исключение (Объект
- исключение должен быть объектом пользовательского класса, пронаследованного от
- Exception). Реализовать интерфейс ICloneable. Добавить возможность работы с элементами
- матрицы в цикле foreach. Примечание. Класс должен содержать не менее 3 различных
- конструкторов.
- */
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace lab5_a_
- {
- class SquareMatrix : ICloneable, IEnumerable
- {
- private double [,] arr { set; get;}
- public uint Size {
- get
- {
- return (uint) arr.GetLength(1);
- }
- }
- public SquareMatrix(int size = 0)
- {
- arr = new double[size,size];
- arr.Initialize();
- }
- public SquareMatrix(SquareMatrix ob)
- {
- arr = (double[,])ob.arr.Clone();
- }
- public SquareMatrix(string[] str)
- {
- int len = str.Length;
- arr = new double[len,len];
- int i = 0;
- foreach(var buf in str)
- {
- int j = 0;
- var temp = buf.Split(' ');
- foreach (var s in temp) double.TryParse(s, out arr[i, j++]);
- i++;
- }
- }
- public SquareMatrix(double [,] arr)
- {
- this.arr = (double[,])arr.Clone();
- }
- public void Print()
- {
- for (int i = 0; i < arr.GetLength(1); ++i)
- {
- for (int j = 0; j < arr.GetLength(1); ++j)
- Console.Write(string.Format("{0} ", arr[i, j]));
- Console.Write("\n");
- }
- }
- public void SetValue()
- {
- string buf ;
- var i = 0;
- Console.WriteLine(@"введите матрицу матрицу размером {0}x{0}(:wq для выхода)
- (цифры вводятся через пробел):", Size);
- while ( (buf = Console.ReadLine() )!= ":wq")
- {
- int j = 0;
- var temp = buf.Split(' ');
- try
- {
- foreach (var s in temp) double.TryParse(s, out arr[i, j++]);
- }
- catch (System.IndexOutOfRangeException) { throw new MyExeption("Ошибка! вы ввели не тот символ или написали слишком много значений, попробуйте ввести строку снова"); }
- i++;
- }
- }
- public void SetAt(uint row, uint column, double num)
- {
- arr[row, column] = num;
- }
- public IEnumerator<double> GetEnumerator()
- {
- foreach (var n in arr) yield return n;
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- public SquareMatrix GetMinor(int row, int column)
- {
- var temp = new double[Size - 1, Size - 1];
- for (int i = 0; i <Size; i++)
- for (int j = 0; j < Size; j++)
- {
- if ((i != row) || (j != column))
- {
- if (i > row && j < column) temp[i - 1, j] = arr[i, j];
- if (i < row && j > column) temp[i, j - 1] = arr[i, j];
- if (i > row && j > column) temp[i - 1, j - 1] = arr[i, j];
- if (i < row && j < column) temp[i, j] = arr[i, j];
- }
- }
- return new SquareMatrix(temp);
- }
- public double Determinant()
- {
- if (Size == 1) return arr[0, 0];
- else if (Size == 2)
- {
- return arr[0, 0] * arr[1, 1] - arr[0, 1] * arr[1, 0];
- }
- else
- {
- double det = 0;
- for (int j = 0; j <Size; j++)
- {
- det += Math.Pow(-1, 0 + j) * arr[0, j] * this.GetMinor(0, j).Determinant();
- }
- return det;
- }
- }
- public void Transp()
- {
- for (int i = 0; i < Size; i++)
- {
- for (int j = 0; j < i; j++)
- {
- var tmp = arr[i, j];
- arr[i, j] = arr[j, i];
- arr[j, i] = tmp;
- }
- }
- }
- public object Clone()
- {
- var newMatrix = (double[,])arr.Clone();
- return new SquareMatrix(newMatrix);
- }
- public static SquareMatrix operator+(SquareMatrix left, SquareMatrix right)
- {
- var temp = new double[left.Size,left.Size];
- for (int i = 0; i < temp.GetLength(1); ++i)
- for (int j = 0; j < temp.GetLength(1); ++j)
- temp[i, j] = left.arr[i, j] + right.arr[i, j];
- return new SquareMatrix(temp);
- }
- public static SquareMatrix operator *(SquareMatrix left, SquareMatrix right)
- {
- var len = left.Size;
- var temp = new double[len,len];
- for (int i = 0; i < len; i++)
- {
- for (int j = 0; j < len; j++)
- {
- for (int k = 0; k < len; k++)
- {
- temp[i, j] += left.arr[i, k] * right.arr[k, j];
- }
- }
- }
- return new SquareMatrix(temp);
- }
- public static SquareMatrix operator/(SquareMatrix left, SquareMatrix right)
- {
- return left * right.Inverse();
- }
- public SquareMatrix Inverse()
- {
- if (this.Determinant() == 0) throw new MyExeption("Невозможно найти обратную марицу");
- int len =(int) Size;
- var temp = new double[len, len];
- var del = 1 / this.Determinant();
- for(int i = 0; i < len; ++ i)
- for(int j =0; j <len; ++j)
- //try
- {
- temp[i, j] = this.GetMinor(i, j).Determinant() * del;
- temp[i, j] *= ((i + j) % 2 == 0) ? 1 : -1;
- }
- /*catch (System.IndexOutOfRangeException ex)
- {
- Console.WriteLine(ex.Message);
- }*/
- var m = new SquareMatrix(temp);
- m.Transp();
- return m;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement