Дан двумерный массив, создать другой массив, строками которого будут диагонали первого массива - C#
Формулировка задачи:
Дан двумерный массив, создать другой массив, строками которого будут диагонали первого массива. Задачу решить с помощью классов. Класс будет содержать два метода: один заполнит массив значениями, второй произведет замену значений строк на значения диагоналей.
Решение задачи: «Дан двумерный массив, создать другой массив, строками которого будут диагонали первого массива»
textual
Листинг программы
using System;
static class IntMatrixOps
{
public static int[,] SwapLineByDiag(this int[,] matr)
{
if (matr.GetLength(0) != matr.GetLength(1)) throw new Exception
("все плохо(метод работает только с квадратными матрицами)");
int[,] m2 = new int[matr.GetLength(0), matr.GetLength(1)];
for (int i = 0; i < matr.GetLength(1); i++)
for (int j = 0; j < matr.GetLength(0); j++)
m2[j, i] = matr[i, i];
return m2;
}
public static void FillWithRandoms(this int[,] matr,Random r = null)
{
r = r ?? new Random();
for (int i = 0; i < matr.GetLength(0); i++)
for (int j = 0; j < matr.GetLength(1); j++) matr[i, j] = r.Next(0,100);
}
public static void Show(this int[,] matr)
{
for (int i = 0; i < matr.GetLength(0); i++)
{
for (int j = 0; j < matr.GetLength(1); j++) Console.Write("{0,3}", matr[i, j]);
Console.WriteLine();
}
}
}
class test
{
static void Main()
{
Random r = new Random();
Console.Write("введите сторону матрицы : ");
int b = int.Parse(Console.ReadLine());
int[,] matrix = new int[b,b];
matrix.FillWithRandoms(r);
Console.WriteLine();
matrix.Show();
Console.WriteLine("\nновая матрица : ");
int[,] matr2 = matrix.SwapLineByDiag();
matr2.Show();
Console.ReadKey(true);
}
}