As an assignment i have to create a spiral matrix where the user inputs the number of rows and number of columns. This is my code for far (first year in college studies, so don't be too hard on me)
Console.Write("Enter n: ");
int n = int.Parse(Console.ReadLine());
int[,] matrix = new int[n, n];
int row = 0;
int col = 0;
string direction = "right";
int maxRotations = n * n;
for (int i = 1; i <= maxRotations; i++)
{
if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))
{
direction = "down";
col--;
row++;
}
if (direction == "down" && (row > n - 1 || matrix[row, col] != 0))
{
direction = "left";
row--;
col--;
}
if (direction == "left" && (col < 0 || matrix[row, col] != 0))
{
direction = "up";
col++;
row--;
}
if (direction == "up" && row < 0 || matrix[row, col] != 0)
{
direction = "right";
row++;
col++;
}
matrix[row, col] = i;
if (direction == "right")
{
col++;
}
if (direction == "down")
{
row++;
}
if (direction == "left")
{
col--;
}
if (direction == "up")
{
row--;
}
}
// display matrica
for (int r = 0; r < n; r++)
{
for (int c = 0; c < n; c++)
{
Console.Write("{0,4}", matrix[r, c]);
}
Console.WriteLine();
}
Console.ReadLine();
I am a bit lost as how to do this.I know how to loop the matrix with the same number for the rows and columns but it should be a non-square matrix.
4 x 3 matrix
8 9 10 1
7 12 11 2
6 5 4 3
5 x 2 matrix
3 4
12 5
11 6
10 7
9 8
Here is the solution I came up with - with some help from the community here :)