Вывести элементы матрицы на экран в следующем порядке - C#
Формулировка задачи:
Помогите пожалуйста, не могу понять как вывести элементы матрицы на экран в следующем порядке:
Решение задачи: «Вывести элементы матрицы на экран в следующем порядке»
textual
Листинг программы
- using System;
- namespace CleanConsole
- {
- class Program
- {
- static void Main(string[] args)
- {
- var matrix = CreateRandomMatrix(4, 4);
- PrintMatrix(matrix);
- Console.WriteLine();
- PrintZigZag(matrix);
- }
- static int[,] CreateRandomMatrix(int rows, int columns)
- {
- var rand = new Random();
- var matrix = new int[rows, columns];
- for (int y = 0; y < rows; ++y)
- for (int x = 0; x < columns; ++x)
- matrix[y, x] = rand.Next(10);
- return matrix;
- }
- static void PrintMatrix(int[,] matrix)
- {
- for (int y = 0; y < matrix.GetLength(0); ++y)
- {
- for (int x = 0; x < matrix.GetLength(1); x++)
- {
- Console.Write($"{matrix[y, x],2}");
- }
- Console.WriteLine();
- }
- }
- static void PrintZigZag(int[,] matrix)
- {
- int rows = matrix.GetLength(0);
- int columns = matrix.GetLength(1);
- for (int i = 0; i < rows + columns - 1; ++i)
- {
- int dx, dy, startX, startY;
- if (i%2 == 0)
- {
- dx = 1;
- startX = (i < rows) ? 0 : i - rows + 1;
- startY = Math.Min(i, rows - 1);
- }
- else
- {
- dx = -1;
- startX = Math.Min(i, columns - 1);
- startY = (i < columns) ? 0 : i - columns + 1;
- }
- dy = -dx;
- while (startX >= 0 && startX < columns && startY >= 0 && startY < rows)
- {
- Console.Write(matrix[startY, startX] + " ");
- startX += dx;
- startY += dy;
- }
- }
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д