- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- namespace huy
- {
- class Program
- {
- static Random rnd = new Random();
- static void Main(string[] args)
- {
- SelectingCommand();
- }
- public static void RulesAndCommands()
- {
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.WriteLine("╔════════════════════════════════════════════════════════════════════╗");
- Console.WriteLine("║Команда для вычисления следа матрицы - trace ║");
- Console.WriteLine("║Команда для транспонирования матрицы - trance ║");
- Console.WriteLine("║Команда для получения суммы матриц двух - + ║");
- Console.WriteLine("║Команда для произведения матрицы на введенное чсисло - *a ║");
- Console.WriteLine("║Команда для получения разности матриц - - ║");
- Console.WriteLine("║Команда для поиска детерминанта - det ║");
- Console.WriteLine("║Команда для выхода из программы - exit ║");
- Console.WriteLine("║Команда для чистки консоли - clear ║");
- Console.WriteLine("╚════════════════════════════════════════════════════════════════════╝");
- Console.ResetColor();
- }
- public static void SelectingCommand()
- {
- string comand;
- do
- {
- Console.WriteLine("help для просмотра списка команд");
- Console.WriteLine("Выберите команду");
- comand = Console.ReadLine();
- switch (comand)
- {
- case "trace":
- SelectionForTrace();
- break;
- case "help":
- RulesAndCommands();
- break;
- case "exit":
- comand = "exit";
- Console.WriteLine("Сайонара...");
- break;
- case "clear":
- Console.Clear();
- break;
- case "+":
- SelectionForSumOfMatrix();
- break;
- case "-":
- SelectionForSubOfMatrix();
- break;
- case "trans":
- SelectionForTrasponing();
- break;
- case "*a":
- SelectionForComOfMatrixAndNum();
- break;
- case "*":
- SelectionForComOfMatrixAndMatrix();
- break;
- case "det":
- SelectionForDeterminant();
- break;
- default:
- Console.WriteLine("Ошибка");
- break;
- }
- } while (comand != "exit");
- }
- public static int[,] CreatingMatrix(int size, int column)
- {
- try
- {
- Console.WriteLine("Вводите значения которые хотите ввести в виде строки");
- Console.WriteLine($"Пример: 1 2 3{Environment.NewLine}" +
- $"\t1 2 3{Environment.NewLine}" +
- $"\t1 2 3 зависит от выбранного вами размера");
- Console.WriteLine();
- int[,] squareMatrix = new int[size, column];
- for (int i = 0; i < size; i++)
- {
- string rowOfArray = Console.ReadLine();
- string[] numbersOfRow = rowOfArray.Split(new char[] { ' ' });
- if (numbersOfRow.Length < column)
- {
- Console.WriteLine("Заданный размер не совпадает с полученным");
- Console.WriteLine();
- return null;
- }
- int[] rowOfArrayInInt = new int[column];
- int numberOfArray;
- for (int u = 0, j = 0; u < numbersOfRow.Length; u++)
- {
- if (!int.TryParse(numbersOfRow[u], out numberOfArray))
- {
- Console.WriteLine("Ошибка при вводе");
- Console.WriteLine();
- return null;
- }
- rowOfArrayInInt[j] = numberOfArray;
- j++;
- }
- for (int v = 0; v < column; v++)
- {
- squareMatrix[i, v] = rowOfArrayInInt[v];
- }
- }
- return squareMatrix;
- }
- catch (Exception)
- {
- Console.WriteLine("Ошибка при вводе, некоректные данные");
- Console.WriteLine();
- return null;
- }
- }
- public static int[,] AnotherMatrix(int size, int column)
- {
- try
- {
- int[,] squareMatrix = new int[size, column];
- for (int i = 0; i < size; i++)
- {
- string rowOfArray = Console.ReadLine();
- string[] numbersOfRow = rowOfArray.Split(new char[] { ' ' });
- if (numbersOfRow.Length < column)
- {
- Console.WriteLine("Заданный размер не совпадает с полученным");
- Console.WriteLine();
- return null;
- }
- int[] rowOfArrayInInt = new int[column];
- int numberOfArray;
- for (int u = 0, j = 0; u < numbersOfRow.Length; u++)
- {
- if (!int.TryParse(numbersOfRow[u], out numberOfArray))
- {
- Console.WriteLine("Ошибка при вводе");
- Console.WriteLine();
- return null;
- }
- rowOfArrayInInt[j] = numberOfArray;
- j++;
- }
- for (int v = 0; v < column; v++)
- {
- squareMatrix[i, v] = rowOfArrayInInt[v];
- }
- }
- return squareMatrix;
- }
- catch (Exception)
- {
- Console.WriteLine("Ошибка при вводе, некоректные данные");
- Console.WriteLine();
- return null;
- }
- }
- public static int[,] CreatingMatrixByRandom(int row, int column)
- {
- Console.WriteLine();
- int[,] matrix = new int[row, column];
- Console.WriteLine("Введите диапозон рандома");
- Console.WriteLine("Минимальное значение");
- int min, notMax;
- while (!int.TryParse(Console.ReadLine(), out min))
- {
- Console.WriteLine("Ошибкка при вводе");
- Console.WriteLine();
- }
- Console.WriteLine("Максимальное значение");
- while (!int.TryParse(Console.ReadLine(), out notMax))
- {
- Console.WriteLine("Ошибкка при вводе");
- Console.WriteLine();
- }
- int max = notMax + 1;
- for (int i = 0; i < row; i++)
- {
- for (int u = 0; u < column; u++)
- {
- matrix[i, u] = rnd.Next(min, max);
- }
- }
- Console.WriteLine("Заспавнившаяся матрица");
- for (int i = 0; i < row; i++)
- {
- for (int u = 0; u < column; u++)
- {
- Console.Write($"{matrix[i, u]} ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- return matrix;
- }
- public static int[,] GettingMatrixFromFile()
- {
- try
- {
- Console.WriteLine();
- Console.WriteLine("Значения должны быть записаны как в примере");
- Console.WriteLine($"Пример: 1 2 3{Environment.NewLine}" +
- $"\t1 2 3{Environment.NewLine}" +
- $"\t1 2 3 зависит от выбранного вами размера");
- Console.WriteLine("Введите полный путь к файлу");
- string path = Console.ReadLine();
- if (!File.Exists(path))
- {
- Console.WriteLine("Файла не существует");
- Console.WriteLine();
- return null;
- }
- StreamReader file = new StreamReader(path);
- string s = file.ReadToEnd();
- file.Close();
- string[] row = s.Split('\n');
- string[] column = row[0].Split(' ');
- int[,] squareMatrix = new int[row.Length, column.Length];
- int t;
- for (int i = 0; i < row.Length; i++)
- {
- column = row[i].Split(' ');
- for (int j = 0; j < column.Length; j++)
- {
- if (!int.TryParse(column[j], out t))
- {
- Console.WriteLine("Ошибка, неопознаный знак");
- Console.WriteLine();
- return null;
- }
- squareMatrix[i, j] = t;
- }
- }
- Console.WriteLine("Матрица в файле:");
- for (int i = 0; i < row.Length; i++)
- {
- for (int j = 0; j < column.Length; j++)
- {
- Console.Write($"{squareMatrix[i, j]} ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- return squareMatrix;
- }
- catch (Exception)
- {
- Console.WriteLine("Ошибка при вводе, некоректные данные");
- Console.WriteLine();
- return null;
- }
- }
- public static void SelectionForTrace()
- {
- Console.WriteLine("Каким способом вы хотите получить матрицу");
- Console.WriteLine("1 - Ввести вручную, 2 - Рандомные матрицы, 3 - загругить из файла");
- string choise = Console.ReadLine();
- Console.WriteLine();
- switch (choise)
- {
- case "1":
- SearchingMatrixTrace();
- break;
- case "2":
- MatrixTraceRandom();
- break;
- case "3":
- MatrixTraceFromFile();
- break;
- default:
- Console.WriteLine("Ошибка при выборе");
- Console.WriteLine();
- break;
- }
- }
- public static void SearchingMatrixTrace()
- {
- Console.WriteLine("След находиться только в квадратных матрицах");
- Console.WriteLine("Введите размерность матрицы (если будет введено например 3, матрица будет размера 3 на 3)");
- Console.Write("Размерность = ");
- int sizeOfMatrix;
- while (!int.TryParse(Console.ReadLine(), out sizeOfMatrix) || sizeOfMatrix <= 0)
- {
- Console.WriteLine("Ошибка при вводе!");
- Console.WriteLine();
- }
- int[,] matrix;
- do
- {
- matrix = CreatingMatrix(sizeOfMatrix, sizeOfMatrix);
- } while (matrix == null);
- int result = 0;
- for (int i = 0; i < sizeOfMatrix; i++)
- {
- result += matrix[i, i];
- }
- Console.WriteLine($"След матрицы равен = {result}");
- }
- public static void MatrixTraceRandom()
- {
- Console.WriteLine("След находиться только в квадратных матрицах");
- Console.WriteLine("Введите размерность матрицы (если будет введено например 3, матрица будет размера 3 на 3)");
- Console.Write("Размерность = ");
- int sizeOfMatrix;
- while (!int.TryParse(Console.ReadLine(), out sizeOfMatrix) || sizeOfMatrix <= 0)
- {
- Console.WriteLine("Ошибка при вводе!");
- Console.WriteLine();
- }
- int[,] matrix = CreatingMatrixByRandom(sizeOfMatrix, sizeOfMatrix);
- int result = 0;
- for (int i = 0; i < sizeOfMatrix; i++)
- {
- result += matrix[i, i];
- }
- Console.WriteLine($"След матрицы равен = {result}");
- }
- public static void MatrixTraceFromFile()
- {
- Console.WriteLine("Замечание: След находиться только в квадратных матрицах");
- int[,] matrix;
- do
- {
- matrix = GettingMatrixFromFile();
- } while (matrix == null);
- int result = 0;
- for (int i = 0; i < matrix.GetLength(0); i++)
- {
- result += matrix[i, i];
- }
- Console.WriteLine($"След матрицы равен = {result}");
- }
- public static void SelectionForTrasponing()
- {
- Console.WriteLine("Каким способом вы хотите получить матрицу");
- Console.WriteLine("1 - Ввести вручную, 2 - Рандомные матрицы, 3 - загругить из файла");
- string choise = Console.ReadLine();
- Console.WriteLine();
- switch (choise)
- {
- case "1":
- TransponingMatrix();
- break;
- case "2":
- TransponingByRandom();
- break;
- case "3":
- TransponingMatrixFromFile();
- break;
- default:
- Console.WriteLine("Ошибка при выборе");
- Console.WriteLine();
- break;
- }
- }
- public static void TransponingMatrix()
- {
- Console.WriteLine("Введите количество строк и столбцов в матрице");
- Console.Write("строк = ");
- int row;
- while (!int.TryParse(Console.ReadLine(), out row) || row <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int column;
- Console.Write("cтолбцов = ");
- while (!int.TryParse(Console.ReadLine(), out column) || column <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int[,] matrix;
- do
- {
- matrix = CreatingMatrix(row, column);
- } while (matrix == null);
- Console.WriteLine("Транспонированная матрица:");
- for (int i = 0; i < column; i++)
- {
- for (int u = 0; u < row; u++)
- {
- Console.Write($"{matrix[u, i]} ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- public static void TransponingByRandom()
- {
- Console.WriteLine("Введите количество строк и столбцов в матрице");
- Console.Write("строк = ");
- int row;
- while (!int.TryParse(Console.ReadLine(), out row) || row <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int column;
- Console.Write("cтолбцов = ");
- while (!int.TryParse(Console.ReadLine(), out column) || column <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int[,] matrix = CreatingMatrixByRandom(row, column);
- Console.WriteLine("Транспонированная матрица:");
- for (int i = 0; i < column; i++)
- {
- for (int u = 0; u < row; u++)
- {
- Console.Write($"{matrix[u, i]} ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- public static void TransponingMatrixFromFile()
- {
- int[,] matrix;
- do
- {
- matrix = GettingMatrixFromFile();
- } while (matrix == null);
- Console.WriteLine("Транспонированная матрица:");
- for (int i = 0; i < matrix.GetLength(1); i++)
- {
- for (int u = 0; u < matrix.GetLength(0); u++)
- {
- Console.Write($"{matrix[u, i]} ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- public static void SelectionForSumOfMatrix()
- {
- Console.WriteLine("Каким способом вы хотите получить матрицу");
- Console.WriteLine("1 - Ввести вручную, 2 - Рандомные матрицы, 3 - загругить из файла");
- string choise = Console.ReadLine();
- Console.WriteLine();
- switch (choise)
- {
- case "1":
- SumOfMatrix();
- break;
- case "2":
- SumOfMatrixByRandom();
- break;
- case "3":
- SumOfMatrixFromFile();
- break;
- default:
- Console.WriteLine("Ошибка при выборе");
- Console.WriteLine();
- break;
- }
- }
- public static void SumOfMatrix()
- {
- Console.WriteLine("Действие - сложение матриц");
- Console.WriteLine("Размерность матриц равна(поэтому)");
- Console.WriteLine("Введите количество строк и столбцов в матрице");
- Console.Write("строк = ");
- int row;
- while (!int.TryParse(Console.ReadLine(), out row) || row <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int column;
- Console.Write("cтолбцов = ");
- while (!int.TryParse(Console.ReadLine(), out column) || column <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Введите первую матрицу");
- int[,] matrix;
- do
- {
- matrix = CreatingMatrix(row, column);
- } while (matrix == null);
- Console.WriteLine("Введите вторую матрицу");
- int[,] matrix1;
- do
- {
- matrix1 = CreatingMatrix(row, column);
- } while (matrix1 == null);
- SumOfMatrixPart2(matrix, matrix1, row, column);
- }
- public static void SumOfMatrixPart2(int[,] matrix1, int[,] matrix2, int row, int column)
- {
- int[,] resultMatrix = new int[row, column];
- for (int i = 0; i < row; i++)
- {
- for (int uq = 0; uq < column; uq++)
- {
- resultMatrix[i, uq] = matrix1[i, uq] + matrix2[i, uq];
- }
- }
- Console.WriteLine("Сумма матриц");
- for (int i = 0; i < row; i++)
- {
- for (int uq = 0; uq < column; uq++)
- {
- Console.Write($"{resultMatrix[i, uq]} ");
- }
- Console.WriteLine();
- }
- }
- public static void SumOfMatrixByRandom()
- {
- Console.WriteLine("Действие - сложение матриц");
- Console.WriteLine("Размерность матриц равна");
- Console.WriteLine("Введите количество строк и столбцов в матрице");
- Console.Write("строк = ");
- int row;
- while (!int.TryParse(Console.ReadLine(), out row) || row <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int column;
- Console.Write("cтолбцов = ");
- while (!int.TryParse(Console.ReadLine(), out column) || column <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Первая матрица:");
- int[,] matrix1 = CreatingMatrixByRandom(row, column);
- Console.WriteLine("Вторая матрица:");
- int[,] matrix2 = CreatingMatrixByRandom(row, column);
- SumOfMatrixPart2(matrix1, matrix2, row, column);
- }
- public static void SumOfMatrixFromFile()
- {
- Console.WriteLine("Действие - сложение матриц");
- Console.WriteLine("Размерность матриц должна быть равна");
- Console.WriteLine("Первая матрица");
- int[,] matrix1;
- do
- {
- matrix1 = GettingMatrixFromFile();
- } while (matrix1 == null);
- Console.WriteLine("Вторая матрица");
- int[,] matrix2;
- do
- {
- matrix2 = GettingMatrixFromFile();
- } while (matrix2 == null);
- if (matrix1.GetLength(0) != matrix2.GetLength(0) || matrix1.GetLength(1) != matrix2.GetLength(1)
- || matrix1.GetLength(0) != matrix1.GetLength(1) || matrix2.GetLength(0) != matrix2.GetLength(1))
- {
- Console.WriteLine("Ошибка, не соответствует размеры");
- Console.WriteLine();
- return;
- }
- SumOfMatrixPart2(matrix1, matrix2, matrix1.GetLength(0), matrix1.GetLength(1));
- }
- public static void SelectionForSubOfMatrix()
- {
- Console.WriteLine("Каким способом вы хотите получить матрицу");
- Console.WriteLine("1 - Ввести вручную, 2 - Рандомные матрицы, 3 - загругить из файла");
- string choise = Console.ReadLine();
- Console.WriteLine();
- switch (choise)
- {
- case "1":
- SubstracionOfMatrix();
- break;
- case "2":
- SubOfMatrixByRandom();
- break;
- case "3":
- SubOfMatrixFromFile();
- break;
- default:
- Console.WriteLine("Ошибка при выборе");
- break;
- }
- }
- public static void SubstracionOfMatrix()
- {
- Console.WriteLine("Действие - разность матриц");
- Console.WriteLine("Размерность матриц равна");
- Console.WriteLine("Введите количество строк и столбцов в матрице");
- Console.Write("строк = ");
- int row;
- while (!int.TryParse(Console.ReadLine(), out row) || row <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int column;
- Console.Write("cтолбцов = ");
- while (!int.TryParse(Console.ReadLine(), out column) || column <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Введите первую матрицу");
- int[,] matrix;
- do
- {
- matrix = CreatingMatrix(row, column);
- } while (matrix == null);
- Console.WriteLine("Введите вторую матрицу");
- int[,] matrix1;
- do
- {
- matrix1 = CreatingMatrix(row, column);
- } while (matrix1 == null);
- SubstractionOfMatrixPart2(matrix, matrix1, row, column);
- }
- public static void SubstractionOfMatrixPart2(int[,] matrix1, int[,] matrix2, int row, int column)
- {
- int[,] resultMatrix = new int[row, column];
- for (int i = 0; i < row; i++)
- {
- for (int uq = 0; uq < column; uq++)
- {
- resultMatrix[i, uq] = matrix1[i, uq] - matrix2[i, uq];
- }
- }
- Console.WriteLine("Разность матриц равна");
- for (int i = 0; i < row; i++)
- {
- for (int uq = 0; uq < column; uq++)
- {
- Console.Write($"{resultMatrix[i, uq]} ");
- }
- Console.WriteLine();
- }
- }
- public static void SubOfMatrixByRandom()
- {
- Console.WriteLine("Действие - разность матриц");
- Console.WriteLine("Размерность матриц равна");
- Console.WriteLine("Введите количество строк и столбцов в матрице");
- Console.Write("строк = ");
- int row;
- while (!int.TryParse(Console.ReadLine(), out row) || row <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int column;
- Console.Write("cтолбцов = ");
- while (!int.TryParse(Console.ReadLine(), out column) || column <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Первая матрица:");
- int[,] matrix1 = CreatingMatrixByRandom(row, column);
- Console.WriteLine("Вторая матрица:");
- int[,] matrix2 = CreatingMatrixByRandom(row, column);
- SubstractionOfMatrixPart2(matrix1, matrix2, row, column);
- }
- public static void SubOfMatrixFromFile()
- {
- Console.WriteLine("Действие - разность матриц");
- Console.WriteLine("Размерность матриц должна быть равна");
- Console.WriteLine("Первая матрица");
- int[,] matrix1;
- do
- {
- matrix1 = GettingMatrixFromFile();
- } while (matrix1 == null);
- Console.WriteLine("Вторая матрица");
- int[,] matrix2;
- do
- {
- matrix2 = GettingMatrixFromFile();
- } while (matrix2 == null);
- if (matrix1.GetLength(0) != matrix2.GetLength(0) || matrix1.GetLength(1) != matrix2.GetLength(1)
- || matrix1.GetLength(0) != matrix1.GetLength(1) || matrix2.GetLength(0) != matrix2.GetLength(1))
- {
- Console.WriteLine("Ошибка, не соответствует размеры");
- Console.WriteLine();
- return;
- }
- SubstractionOfMatrixPart2(matrix1, matrix2, matrix1.GetLength(0), matrix1.GetLength(1));
- }
- public static void SelectionForComOfMatrixAndNum()
- {
- Console.WriteLine("Каким способом вы хотите получить матрицу");
- Console.WriteLine("1 - Ввести вручную, 2 - Рандомные матрицы, 3 - загругить из файла");
- string choise = Console.ReadLine();
- switch (choise)
- {
- case "1":
- CompositionMatrixWithNumber();
- break;
- case "2":
- CompositionMatrixWithNumberByRandom();
- break;
- case "3":
- ComMatrixWithNumberFromFile();
- break;
- default:
- Console.WriteLine("Ошибка при выборе");
- Console.WriteLine();
- break;
- }
- }
- public static void CompositionMatrixWithNumber()
- {
- Console.WriteLine("Действие - умножение матрицы на число");
- Console.WriteLine("Введите количество строк и столбцов в матрице");
- Console.Write("строк = ");
- int row;
- while (!int.TryParse(Console.ReadLine(), out row) || row <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int column;
- Console.Write("cтолбцов = ");
- while (!int.TryParse(Console.ReadLine(), out column) || column <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Введите матрицу");
- int[,] matrix;
- do
- {
- matrix = CreatingMatrix(row, column);
- } while (matrix == null);
- Console.WriteLine("Введите число на которое надо умножить матрицу");
- int lyamda;
- while (!int.TryParse(Console.ReadLine(), out lyamda))
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- }
- Console.WriteLine("Получившаяся матрица");
- for (int i = 0; i < row; i++)
- {
- for (int u = 0; u < column; u++)
- {
- Console.Write($"{matrix[i, u] * lyamda} ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- public static void CompositionMatrixWithNumberByRandom()
- {
- Console.WriteLine("Действие - умножение матрицы на число");
- Console.WriteLine("Введите количество строк и столбцов в матрице");
- Console.Write("строк = ");
- int row;
- while (!int.TryParse(Console.ReadLine(), out row) || row <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int column;
- Console.Write("cтолбцов = ");
- while (!int.TryParse(Console.ReadLine(), out column) || column <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- int[,] matrix = CreatingMatrixByRandom(row, column);
- Console.WriteLine("Введите число на которое надо умножить матрицу");
- int lyamda;
- while (!int.TryParse(Console.ReadLine(), out lyamda))
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- }
- Console.WriteLine("Получившаяся матрица");
- for (int i = 0; i < row; i++)
- {
- for (int u = 0; u < column; u++)
- {
- Console.Write($"{matrix[i, u] * lyamda} ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- public static void ComMatrixWithNumberFromFile()
- {
- Console.WriteLine("Действие - умножение матрицы на число");
- int[,] matrix;
- do
- {
- matrix = GettingMatrixFromFile();
- } while (matrix == null);
- Console.WriteLine("Введите число на которое надо умножить матрицу");
- int lyamda;
- while (!int.TryParse(Console.ReadLine(), out lyamda))
- {
- Console.WriteLine("Ошибка");
- }
- Console.WriteLine("Получившаяся матрица");
- for (int i = 0; i < matrix.GetLength(0); i++)
- {
- for (int u = 0; u < matrix.GetLength(1); u++)
- {
- Console.Write($"{matrix[i, u] * lyamda} ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- public static void SelectionForComOfMatrixAndMatrix()
- {
- Console.WriteLine("Каким способом вы хотите получить матрицу");
- Console.WriteLine("1 - Ввести вручную, 2 - Рандомные матрицы, 3 - загругить из файла");
- string choise = Console.ReadLine();
- switch (choise)
- {
- case "1":
- CompositionWithAnotherMatrix();
- break;
- case "2":
- CompositionWithAnotherMatrixByRandom();
- break;
- case"3":
- ComMatrixesFromFile();
- break;
- default:
- Console.WriteLine("Ошибка при выборе");
- break;
- }
- }
- public static void CompositionWithAnotherMatrix()
- {
- Console.WriteLine("Действие - умножение двух матриц");
- Console.WriteLine("Замечание: Количество столбцов в первой матрице равно количеству строк во второй");
- Console.WriteLine("Введите количество строк первой матрицы");
- Console.Write("строк первой матрицы = ");
- int row1;
- while (!int.TryParse(Console.ReadLine(), out row1) || row1 <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Введите количество столбцов первой и строк второй матриц");
- int column1row2;
- Console.Write("количество столбцов первой и строк второй матриц = ");
- while (!int.TryParse(Console.ReadLine(), out column1row2) || column1row2 <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Введите количество столбцов второй матрицы");
- int column2;
- Console.Write("cтолбцов второй матрицы = ");
- while (!int.TryParse(Console.ReadLine(), out column2) || column2 <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Введите первую матрицу");
- int[,] matrix1;
- do
- {
- matrix1 = CreatingMatrix(row1, column1row2);
- } while (matrix1 == null);
- Console.WriteLine("Введите вторую матрицу");
- int[,] matrix2;
- do
- {
- matrix2 = CreatingMatrix(column1row2, column2);
- } while (matrix2 == null);
- CompositionWithAnotherMatrixPart2(matrix1, matrix2, row1, column1row2, column2);
- }
- public static void CompositionWithAnotherMatrixPart2(int[,] matrix1, int[,] matrix2, int row1, int column1row2, int column2)
- {
- int[,] resultMatrix = new int[row1, column2];
- for (int i = 0; i < row1; i++)
- {
- for (int u = 0; u < column2; u++)
- {
- for (int j = 0; j < column1row2; j++)
- {
- resultMatrix[i, u] += matrix1[i, j] * matrix2[j, u];
- }
- }
- }
- Console.WriteLine("Произведение матриц:");
- for (int i = 0; i < row1; i++)
- {
- for (int u = 0; u < column2; u++)
- {
- Console.Write($"{resultMatrix[i, u]} ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- public static void CompositionWithAnotherMatrixByRandom()
- {
- Console.WriteLine("Действие - умножение двух матриц");
- Console.WriteLine("Замечание: Количество столбцов в первой матрице равно количеству строк во второй");
- Console.WriteLine("Введите количество строк первой матрицы");
- Console.Write("строк первой матрицы = ");
- int row1;
- while (!int.TryParse(Console.ReadLine(), out row1) || row1 <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Введите количество столбцов первой и строк второй матриц");
- int column1row2;
- Console.Write("количество столбцов первой и строк второй матриц = ");
- while (!int.TryParse(Console.ReadLine(), out column1row2) || column1row2 <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Введите количество столбцов второй матрицы");
- int column2;
- Console.Write("cтолбцов второй матрицы = ");
- while (!int.TryParse(Console.ReadLine(), out column2) || column2 <= 0)
- {
- Console.WriteLine("Ошибка");
- Console.WriteLine();
- return;
- }
- Console.WriteLine("Первая матрица:");
- int[,] matrix1 = CreatingMatrixByRandom(row1, column1row2);
- Console.WriteLine("Вторая матрица:");
- int[,] matrix2 = CreatingMatrixByRandom(column1row2, column2);
- CompositionWithAnotherMatrixPart2(matrix1, matrix2, row1, column1row2, column2);
- }
- public static void ComMatrixesFromFile()
- {
- Console.WriteLine("Действие - умножение двух матриц");
- Console.WriteLine("Замечание: Количество столбцов в первой матрице равно количеству строк во второй");
- int[,] matrix1;
- Console.WriteLine("Первая матрица:");
- do
- {
- matrix1 = GettingMatrixFromFile();
- } while (matrix1 == null);
- int[,] matrix2;
- Console.WriteLine("Вторая матрица");
- do
- {
- matrix2 = GettingMatrixFromFile();
- } while (matrix2 == null);
- CompositionWithAnotherMatrixPart2(matrix1, matrix2, matrix1.GetLength(0), matrix1.GetLength(1), matrix2.GetLength(1));
- }
- public static void SelectionForDeterminant()
- {
- Console.WriteLine("Каким способом вы хотите получить матрицу");
- Console.WriteLine("1 - Ввести вручную, 2 - Рандомные матрицы, 3 - загругить из файла");
- string choise = Console.ReadLine();
- switch (choise)
- {
- case "1":
- DeterminantByHands();
- break;
- case "2":
- DeterminantByRandom();
- break;
- case "3":
- DeterminantFromFile();
- break;
- default:
- Console.WriteLine("Ошибка при выборе");
- break;
- }
- }
- public static void DeterminantByHands()
- {
- try
- {
- Console.WriteLine("Замечание: матрица должна быть квадратной");
- Console.WriteLine("Введите размерность матрицы (если будет введено например 3, матрица будет размера 3 на 3)");
- Console.Write("Размерность = ");
- int sizeOfMatrix;
- while (!int.TryParse(Console.ReadLine(), out sizeOfMatrix) || sizeOfMatrix <= 0)
- {
- Console.WriteLine("Ошибка при вводе!");
- Console.WriteLine();
- }
- int[,] matrix;
- do
- {
- matrix = CreatingMatrix(sizeOfMatrix, sizeOfMatrix);
- } while (matrix == null);
- int determinantMatrix = Determinant(matrix);
- Console.WriteLine($"Детерминант матрицы = {determinantMatrix}");
- Console.WriteLine();
- }
- catch(OverflowException)
- {
- Console.WriteLine();
- }
- catch
- {
- Console.WriteLine("Ошибка");
- }
- }
- public static void DeterminantByRandom()
- {
- try
- {
- Console.WriteLine("Замечание: матрица должна быть квадратной");
- Console.WriteLine("Введите размерность матрицы (если будет введено например 3, матрица будет размера 3 на 3)");
- Console.Write("Размерность = ");
- int sizeOfMatrix;
- while (!int.TryParse(Console.ReadLine(), out sizeOfMatrix) || sizeOfMatrix <= 0)
- {
- Console.WriteLine("Ошибка при вводе!");
- }
- int[,] matrix = CreatingMatrixByRandom(sizeOfMatrix, sizeOfMatrix);
- int determinantMatrix = Determinant(matrix);
- Console.WriteLine($"Детерминант матрицы = {determinantMatrix}");
- Console.WriteLine();
- }
- catch (OverflowException)
- {
- Console.WriteLine();
- }
- catch
- {
- Console.WriteLine("Ошибка");
- }
- }
- public static void DeterminantFromFile()
- {
- try
- {
- Console.WriteLine("Детерминант находиться только в квадратных матрицах");
- int[,] matrix;
- do
- {
- matrix = GettingMatrixFromFile();
- } while (matrix == null);
- int detetrminant = Determinant(matrix);
- Console.WriteLine($"Детерминант = {detetrminant}");
- }
- catch(InvalidOperationException)
- {
- Console.WriteLine("Неверный размер матрицы");
- }
- catch (OverflowException)
- {
- Console.WriteLine();
- }
- catch
- {
- Console.WriteLine("Ошибка сенпай");
- }
- }
- public static int Determinant(int[,] matrix)
- {
- if (matrix.GetLength(1) == matrix.GetLength(0))
- {
- // Если матрица 2х2
- if (matrix.Length == 4)
- {
- Console.WriteLine(Environment.NewLine + "Определитель матрицы равен:");
- Console.WriteLine(matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]);
- }
- int sign = 1;
- int[,] minor = new int[matrix.GetLength(0) - 1, matrix.GetLength(0) - 1];
- // Нахождение минора.
- for (int i = 1; i < matrix.GetLength(1); i++)
- {
- for (int j = 0; j < matrix.GetLength(0) - 1; j++)
- {
- minor[i - 1, j] = matrix[i, j];
- }
- for (int j = matrix.GetLength(0); j < matrix.GetLength(1); j++)
- {
- minor[i - 1, j - 1] = matrix[i, j];
- }
- }
- int det = 0;
- // Нахождение определителя.
- for (int i = 0; i < matrix.GetLength(0); i++)
- {
- det += sign * matrix[0, i] * Determinant(minor);
- sign = -sign;
- }
- return det;
- }
- else
- {
- int? nol = null;
- return (int)nol;
- }
- }
- }
- }