Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- namespace MatrixFromFile
- {
- class Program
- {
- static void Main(string[] args)
- {
- decimal[,] matrix = null;
- using (var file = File.OpenText("matrix.txt"))
- {
- var rows = int.Parse(file.ReadLine());
- var cols = int.Parse(file.ReadLine());
- matrix = new decimal[rows, cols];
- var line = file.ReadLine();
- var r = 0; //ред, започва от 0
- while (line != null)
- {
- var strValues = line.Split(' '); // takes each element from the row
- for (int c = 0; c < strValues.Length; c++)
- {
- matrix[r, c] = decimal.Parse(strValues[c]); // cast each element to decimal
- }
- line = file.ReadLine();
- ++r;
- }
- PrintMatrix(matrix); // this function prints the matrix
- Console.WriteLine("Identity = {0}", CheckIdentity(matrix)); // function tha checks whether the matrix has only 1 on its main diagonal
- }
- }
- static void PrintMatrix(decimal[,] matrix)
- {
- for (int r = 0; r < matrix.GetLength(0); r++) // rows
- {
- for (int c = 0; c < matrix.GetLength(1); c++) // colws
- {
- Console.Write($"{matrix[r,c]}" + "\t");
- }
- Console.WriteLine();
- }
- }
- static bool CheckIdentity (decimal [,] m)
- {
- if (m.GetLength(0) != m.GetLength(1)) //проверява дали е квадратна матрицата
- {
- return false;
- }
- for (int r = 0; r < m.GetLength(0); r++) // rows и е квадратна матрица
- {
- for (int c = 0; c < m.GetLength(1); c++) // cols
- {
- if (r == c && m[r, c] != 1)
- {
- return false;
- }
- else if (r != c && m[r, c] != 0)
- {
- return false;
- }
- }
- }
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement