using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab { internal class Matrices { public static DataTable CreateMatrix(int rows, int cols, string prefix) { DataTable dt = new DataTable(); for (int col = 0; col < cols; col++) { dt.Columns.Add($"{prefix}{col + 1}", typeof(double)); } for (int row = 0; row < rows; row++) { DataRow dr = dt.NewRow(); for (int col = 0; col < cols; col++) { dr[col] = 0; } dt.Rows.Add(dr); } return dt; } public static DataTable CreateMatrixInts(int rows, int cols, string prefix) { DataTable dt = new DataTable(); for (int col = 0; col < cols; col++) { dt.Columns.Add($"{prefix}{col + 1}", typeof(int)); } for (int row = 0; row < rows; row++) { DataRow dr = dt.NewRow(); for (int col = 0; col < cols; col++) { dr[col] = 0; } dt.Rows.Add(dr); } return dt; } public static void RandomFill(DataTable dt, int minIncl, int maxIncl) { Random rng = new Random(); for (int row = 0; row < dt.Rows.Count; row++) { for (int col = 0; col < dt.Columns.Count; col++) { dt.Rows[row][col] = (double)rng.Next(minIncl, maxIncl + 1); } } } public static int[,] ToArray(DataTable dt) { int rows = dt.Rows.Count; int cols = dt.Columns.Count; var array = new int[rows, cols]; for (int row =0; row < rows; row++) { for (int col = 0; col < cols; col++) { object cell = dt.Rows[row][col]; double num = 0; if (cell is null || cell == DBNull.Value) { num = 0; } else if (cell is double d) { num = d; } else if (cell is int i) { num = i; } else { if (!Parsers.TryParseDouble(cell.ToString(), out num)) num = 0; } if (double.IsNaN(num) || double.IsInfinity(num)) num = 0; if (num > int.MaxValue) num = int.MaxValue; if (num < int.MinValue) num = int.MinValue; array[row, col] = Convert.ToInt32(num); } } return array; } public static DataTable FromArray(int[,] array, string prefix) { int rows = array.GetLength(0); int cols = array.GetLength(1); var dt = CreateMatrix(rows, cols, prefix); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { dt.Rows[row][col] = array[row, col]; } } return dt; } } }