Matrix.cs

92 lines | 2.626 kB Blame History Raw Download
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ExpressionOperatorProxy.Generic.MathOperatorProxy;

namespace ExpressionOperatorProxy.Generic.Collection
{
    //Универсальная матрица
    public class Matrix<T>
    {
        OperatorProxy<T>[][] _matrix;

        public int Height => _matrix.Length;
        public int Weight => Height != 0 
            ? _matrix.First().Length 
            : 0;


        public Matrix(int Height, int weight)
        {
            _matrix = new OperatorProxy<T>[Height][];

            foreach (var i in Enumerable.Range(0, Height))
                _matrix[i] = new OperatorProxy<T>[weight];                
        }
        public Matrix(IEnumerable<IEnumerable<T>> data)
        {
           _matrix = data
                .Select(e => 
                    e.Select(e2 => 
                        new OperatorProxy<T>(e2))
                    .ToArray())
                .ToArray();
        }


        public T this[int H, int W]
        {
            set => _matrix[H][W].Value = value;
            get => _matrix[H][W].Value;
        }

        public static Matrix<T> operator +(Matrix<T> operator1, Matrix<T> operator2)
        {
            if (operator1.Height != operator2.Height
                || operator1.Weight != operator2.Weight)
                throw new Exception();

            Matrix<T> res = new Matrix<T>(operator2.Height, operator2.Weight);

            for (int i = 0; i < operator1.Height; i++)
                for (int j = 0; j < operator1.Weight; j++)              
                    res._matrix[i][j] = operator1._matrix[i][j] + operator2._matrix[i][j];                

            return res;
        }
        public static Matrix<T> operator -(Matrix<T> operator1, Matrix<T> operator2)
        {
            if (operator1.Height != operator2.Height
                || operator1.Weight != operator2.Weight)
                throw new Exception();

            Matrix<T> res = new Matrix<T>(operator2.Height, operator2.Weight);

            for (int i = 0; i < operator1.Height; i++)
                for (int j = 0; j < operator2.Weight; j++)
                    res._matrix[i][j] = operator1._matrix[i][j] - operator2._matrix[i][j];

            return res;
        }


        public override string ToString()
        {
            StringBuilder res = new StringBuilder();

            foreach (var row in _matrix)
            {
                foreach (var elem in row)
                    res.Append(elem + " ");
                res.Append('\n');
            }

            return res.ToString();
        }

    }
}