Advertisement
Guest User

Untitled

a guest
Jan 16th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.35 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3.  
  4. namespace MatrixFromFile
  5. {
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             decimal[,] matrix = null;
  11.             using (var file = File.OpenText("matrix.txt"))
  12.             {
  13.                 var rows = int.Parse(file.ReadLine());
  14.                 var cols = int.Parse(file.ReadLine());
  15.                 matrix = new decimal[rows, cols];
  16.                 var line = file.ReadLine();
  17.                 var r = 0; //ред, започва от 0
  18.                 while (line != null)
  19.                 {
  20.                     var strValues = line.Split(' '); // takes each element from the row
  21.                     for (int c = 0; c < strValues.Length; c++)
  22.                     {
  23.                         matrix[r, c] = decimal.Parse(strValues[c]); // cast each element to decimal
  24.                     }
  25.                     line = file.ReadLine();
  26.                     ++r;
  27.                 }
  28.                 PrintMatrix(matrix); // this function prints the matrix
  29.                 Console.WriteLine("Identity = {0}", CheckIdentity(matrix)); // function tha checks whether the matrix has only 1 on its main diagonal
  30.             }
  31.  
  32.         }
  33.         static void PrintMatrix(decimal[,] matrix)
  34.         {
  35.             for (int r = 0; r < matrix.GetLength(0); r++) // rows
  36.             {
  37.                 for (int c = 0; c < matrix.GetLength(1); c++) // colws
  38.                 {
  39.                     Console.Write($"{matrix[r,c]}" + "\t");
  40.                 }
  41.                 Console.WriteLine();
  42.             }
  43.         }
  44.  
  45.         static bool CheckIdentity (decimal [,] m)
  46.         {
  47.             if (m.GetLength(0) != m.GetLength(1)) //проверява дали е квадратна матрицата
  48.             {
  49.                 return false;
  50.             }
  51.  
  52.             for (int r = 0; r < m.GetLength(0); r++) // rows и е квадратна матрица
  53.             {
  54.                 for (int c = 0; c < m.GetLength(1); c++) // cols
  55.                 {
  56.                     if (r == c && m[r, c] != 1)
  57.                     {
  58.                         return false;
  59.                     }
  60.                     else if (r != c && m[r, c] != 0)
  61.                     {
  62.                         return false;
  63.                     }
  64.                 }
  65.             }
  66.             return true;
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement