How to resolve the algorithm Spiral matrix step by step in the C# programming language
How to resolve the algorithm Spiral matrix step by step in the C# programming language
Table of Contents
Problem Statement
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Spiral matrix step by step in the C# programming language
The provided C# code generates a spiral matrix of a given size n
, where each element represents its position in the spiral. Let's break down the code in detail:
Method 1: Spiral
This method generates a 2D array result
to represent the spiral matrix. It uses the following algorithm:
-
It initializes variables to track the current position (
pos
), number of elements to fill in each side of the spiral (count
), current value to fill in (value
), and a running sum of indices (sum
). -
It enters a
do-while
loop that continues as long ascount
is greater than 0. -
Inside the loop:
- It calculates the
value
based on the direction it's filling (either clockwise or counterclockwise). - It fills
count
elements in the current direction, incrementingsum
and setting the corresponding elements inresult
topos
. - It updates
value
andcount
to prepare for filling the next side of the spiral.
- It calculates the
Method 2: PrintArray
This method is used to print the 2D array array
in a formatted manner. It pads the numbers with spaces to align them in columns, making the output visually pleasing.
Method 3: CreateMatrix
This method generates a spiral matrix using a different algorithm. It uses four arrays dx
and dy
to represent the directions in which to fill the matrix.
- It initializes variables
x
,y
,c
, and the matrixm
. - It iterates through the matrix in a spiral pattern, filling in the elements based on the directions defined in
dx
anddy
. - It increments the counter
c
to fill in the spiral with sequential numbers.
Method 4: Print
This method is used to print the generated matrix m
in a formatted manner, padding the numbers with spaces to align them in columns for better readability.
Main Program:
- It reads the order
n
of the spiral matrix from the user. - It creates an instance of the
spiral
class. - It enters a nested loop to fill in the spiral matrix using the
func
method. - The
func
method calculates the index of each element based on its position in the spiral. - It prints the generated spiral matrix using the
Console.WriteLine()
method.
Additional Notes:
- The
spiral
class contains a few additional methods that are not used in this specific example. - The
func
method in thespiral
class is a complex calculation to determine the index of each element in the spiral matrix based on its position.
Output:
The output of the code will be a spiral matrix of the specified order, with each element representing its position in the spiral.
Source code in the csharp programming language
public int[,] Spiral(int n) {
int[,] result = new int[n, n];
int pos = 0;
int count = n;
int value = -n;
int sum = -1;
do {
value = -1 * value / n;
for (int i = 0; i < count; i++) {
sum += value;
result[sum / n, sum % n] = pos++;
}
value *= n;
count--;
for (int i = 0; i < count; i++) {
sum += value;
result[sum / n, sum % n] = pos++;
}
} while (count > 0);
return result;
}
// Method to print arrays, pads numbers so they line up in columns
public void PrintArray(int[,] array) {
int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;
for (int i = 0; i < array.GetLength(0); i++) {
for (int j = 0; j < array.GetLength(1); j++) {
Console.Write(array[i, j].ToString().PadLeft(n, ' '));
}
Console.WriteLine();
}
}
//generate spiral matrix for given N
int[,] CreateMatrix(int n){
int[] dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0};
int x = 0, y = -1, c = 0;
int[,] m = new int[n,n];
for (int i = 0, im = 0; i < n + n - 1; ++i, im = i % 4)
for (int j = 0, jlen = (n + n - i) / 2; j < jlen; ++j)
m[x += dx[im],y += dy[im]] = ++c;
return n;
}
//print aligned matrix
void Print(int[,] matrix) {
var len = (int)Math.Ceiling(Math.Log10(m.GetLength(0) * m.GetLength(1)))+1;
for(var y = 0; y<m.GetLength(1); y++){
for(var x = 0; x<m.GetLength(0); x++){
Console.Write(m[y, x].ToString().PadRight(len, ' '));
}
Console.WriteLine();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace spiralmat
{
class spiral
{
public static int lev;
int lev_lim, count, bk, cd, low, l, m;
spiral()
{
lev = lev_lim = count = bk = cd = low = l = m = 0;
}
void level(int n1, int r, int c)
{
lev_lim = n1 % 2 == 0 ? n1 / 2 : (n1 + 1) / 2;
if ((r <= lev_lim) && (c <= lev_lim))
lev = Math.Min(r, c);
else
{
bk = r > c ? (n1 + 1) - r : (n1 + 1) - c;
low = Math.Min(r, c);
if (low <= lev_lim)
cd = low;
lev = cd < bk ? cd : bk;
}
}
int func(int n2, int xo, int lo)
{
l = xo;
m = lo;
count = 0;
level(n2, l, m);
for (int ak = 1; ak < lev; ak++)
count += 4 * (n2 - 1 - 2 * (ak - 1));
return count;
}
public static void Main(string[] args)
{
spiral ob = new spiral();
Console.WriteLine("Enter Order..");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("The Matrix of {0} x {1} Order is=>\n", n, n);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
Console.Write("{0,3:D} ",
ob.func(n, i, j)
+ Convert.ToInt32(
((j >= i) && (i == lev))
? ((j - i) + 1)
: ((j == ((n + 1) - lev) && (i > lev) && (i <= j)))
? (n - 2 * (lev - 1) + (i - 1) - (n - j))
: ((i == ((n + 1) - lev) && (j < i)))
? ((n - 2 * (lev - 1)) + ((n - 2 * (lev - 1)) - 1) + (i - j))
: ((j == lev) && (i > lev) && (i < ((n + 1) - lev)))
? ((n - 2 * (lev - 1)) + ((n - 2 * (lev - 1)) - 1) + ((n - 2 * (lev - 1)) - 1) + (((n + 1) - lev) - i))
: 0));
Console.WriteLine();
}
Console.ReadKey();
}
}
}
INPUT:-
Enter order..
5
OUTPUT:-
The Matrix of 5 x 5 Order is=>
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
INPUT:-
Enter order..
6
OUTPUT:-
The Matrix of 6 x 6 Order is=>
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
You may also check:How to resolve the algorithm Humble numbers step by step in the zkl programming language
You may also check:How to resolve the algorithm Brownian tree step by step in the Scala programming language
You may also check:How to resolve the algorithm Tokenize a string step by step in the D programming language
You may also check:How to resolve the algorithm McNuggets problem step by step in the Picat programming language
You may also check:How to resolve the algorithm Find the intersection of a line with a plane step by step in the Modula-2 programming language