예제 #1
0
        private ResultOrError <Matrix, string> CalculateMatrices(
            IReadOnlyList <Matrix> matrices,
            Func <Matrix, Matrix, ResultOrError <Matrix, string> > operation)
        {
            if (matrices.Count < 2)
            {
                return(ResultOrError <Matrix, string> .FromError("Нужно минимум две матрицы"));
            }

            Matrix result = null;

            for (var i = 1; i < matrices.Count; i++)
            {
                var rightOp       = matrices[i];
                var leftOp        = result ?? matrices[i - 1];
                var resultOrError = operation(leftOp, rightOp);
                if (resultOrError.IsError)
                {
                    return(ResultOrError <Matrix, string> .FromError($"Ошибка при обработке матрицы #{i}: {resultOrError.Error}"));
                }

                result = resultOrError.Result;
            }
            return(ResultOrError <Matrix, string> .FromResult(result));
        }
예제 #2
0
        public async Task <ResultOrError <PagedResult <ExpenseModel> > > GetMany(Guid userId, int pageNumber, int pageSize = 50, DateTimeOffset?fromDate = null, DateTimeOffset?toDate = null)
        {
            if (!await _context.DoesExist <User>(userId))
            {
                return(CommonErrors.UserNotExist);
            }

            var baseQuery = _context.Expenses
                            .Include(x => x.Aggregate)
                            .Include(x => x.ExpenseType)
                            .Where(x => x.Aggregate.UserId == userId);

            if (fromDate.HasValue)
            {
                baseQuery = baseQuery.Where(x => x.Aggregate.AddedDate >= fromDate.Value);
            }

            if (toDate.HasValue)
            {
                baseQuery = baseQuery.Where(x => x.Aggregate.AddedDate <= toDate.Value);
            }

            var totalItems = await baseQuery.CountAsync();

            var items = totalItems == 0
                ? new List <ExpenseModel>()
                : await baseQuery.OrderByDescending(x => x.Aggregate.AddedDate)
                        .Skip((pageNumber - 1) * pageSize)
                        .Take(pageSize)
                        .Select(x => x.ToModel())
                        .ToListAsync();

            return(ResultOrError <PagedResult <ExpenseModel> > .FromResult(
                       new PagedResult <ExpenseModel>(items, totalItems)));
        }
예제 #3
0
        public ResultOrError <IReadOnlyList <Matrix>, string> TransposeAllMatrices(IReadOnlyList <Matrix> matrices)
        {
            var resultMatrices = matrices
                                 .Select(_matrixCalculator.TransposeMatrix)
                                 .ToArray();

            return(ResultOrError <IReadOnlyList <Matrix>, string> .FromResult(resultMatrices));
        }
예제 #4
0
        public ResultOrError <Matrix, string> AddMatrices(Matrix leftOp, Matrix rightOp)
        {
            if (leftOp.Width != rightOp.Width || leftOp.Height != rightOp.Height)
            {
                return(ResultOrError <Matrix, string> .FromError("У матриц при сложении не совпали размеры"));
            }
            var newMatrix = new int[leftOp.ValuesOneDimensional.Length];

            for (var i = 0; i < leftOp.ValuesOneDimensional.Length; i++)
            {
                newMatrix[i] = leftOp.ValuesOneDimensional[i] + rightOp.ValuesOneDimensional[i];
            }
            return(ResultOrError <Matrix, string> .FromResult(new Matrix(leftOp.Height, leftOp.Width, newMatrix)));
        }
예제 #5
0
        private ResultOrError <Matrix, string> ParseMatrix(string s)
        {
            var    lines          = s.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToArray();
            var    firstLineWidth = 0;
            Matrix result         = null;

            for (var i = 0; i < lines.Length; i++)
            {
                var line = lines[i].Split(' ')
                           .Select(intString => int.TryParse(intString, out var x)
                                                ? ResultOrError <int, string> .FromResult(x)
                                                : ResultOrError <int, string> .FromError($"{intString} не является валидным числом"))
                           .ToArray();

                if (!line.Any())
                {
                    return(ResultOrError <Matrix, string> .FromError("В матрице не могут быть пустые строки"));
                }
                if (line.Any(n => n.IsError))
                {
                    return(ResultOrError <Matrix, string> .FromError(line.First(n => n.IsError).Error));
                }

                if (i == 0)
                {
                    firstLineWidth = line.Length;
                    result         = new Matrix(lines.Length, line.Length);
                }

                if (line.Length != firstLineWidth)
                {
                    return(ResultOrError <Matrix, string> .FromError(
                               $"Число элементов в строке #{i + 1} отличается от первой строки"));
                }

                for (var j = 0; j < firstLineWidth; j++)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    result.ValuesOneDimensional[i * firstLineWidth + j] = line[j].Result;
                }
            }

            return(ResultOrError <Matrix, string> .FromResult(result));
        }
예제 #6
0
        public ResultOrError <CalculationTask, string> GetTaskDetails()
        {
            using (var streamReader = _fileReadStreamProvider.GetFileContent())
            {
                var text  = streamReader.ReadToEnd();
                var parts = text.Split(new[] { Environment.NewLine + Environment.NewLine },
                                       StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length < 2)
                {
                    return(ResultOrError <CalculationTask, string> .FromError("Некорректный формат"));
                }

                var operation = ParseOperation(parts.First());
                if (operation == null)
                {
                    return(ResultOrError <CalculationTask, string> .FromError($"Неизвестная операция {parts.First()}"));
                }

                if (TwoOperandsOperations.Contains(operation.Value) && parts.Length < 3)
                {
                    return(ResultOrError <CalculationTask, string> .FromError(
                               "Для сложения/вычитания/умножения нужно как минимум две матрицы"));
                }

                var matrices = new Matrix[parts.Length - 1];
                for (var i = 1; i < parts.Length; i++)
                {
                    var matrixOrError = ParseMatrix(parts[i]);
                    if (matrixOrError.IsError)
                    {
                        return(ResultOrError <CalculationTask, string> .FromError(
                                   $"Ошибка в матрице #{i}: {matrixOrError.Error}"));
                    }

                    matrices[i - 1] = matrixOrError.Result;
                }

                return(ResultOrError <CalculationTask, string> .FromResult(new CalculationTask
                {
                    Matrices = matrices,
                    Operation = operation.Value
                }));
            }
        }
예제 #7
0
        public ResultOrError <Matrix, string> MultiplyMatrices(Matrix leftOp, Matrix rightOp)
        {
            if (leftOp.Width != rightOp.Height)
            {
                return(ResultOrError <Matrix, string> .FromError("У матриц при умножении не совпали размеры"));
            }

            var result = new Matrix(leftOp.Height, rightOp.Width);

            for (int i = 0; i < leftOp.Height; i++)
            {
                for (int j = 0; j < rightOp.Width; j++)
                {
                    var value = 0;
                    for (int k = 0; k < leftOp.Width; k++)
                    {
                        value += leftOp[i, k] * rightOp[k, j];
                    }

                    result[i, j] = value;
                }
            }
            return(ResultOrError <Matrix, string> .FromResult(result));
        }