Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How I can do this in python ?

+6 votes
asked Feb 16 by Shahriyor Yuldashev (690 points)

n is equal to the number of columns of a matrix and the number of rows of a matrix. n is given. And you should make nxn - matrix. If n is equal to 5, the values of the matrix should be as shown below.

matrix = [[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]]

Or if n is equal to 3, the values of the matrix should be as shown below.

matrix = [[1, 2, 3], 

                 [8, 9, 4],

                 [7, 6, 5]]

That is, the values of the matrix should be as a circle. How I can do this in python?

1 Answer

+1 vote
answered Feb 16 by Peter Minarik (55,660 points)
edited Feb 17 by Peter Minarik

So basically you'll need to fill up a matrix in a spiral pattern.

Here's a pseudo-code for it so you can write the actual Python code (it's an assignment, you should work on it and not just simply get a ready solution). Of course, there are many solutions, this is just one proposal.

The idea is to use a state machine to follow the spiral pattern: move right, then down, then left, then up and then it starts over until the whole matrix is filled.

var n = InputFromUser();
var array[n, n];
var horizontal_min = 0;
var horizontal_max = n - 1;
var vertical_min = 0;
var vertical_max = n - 1;
var totalNumbers = n * n;

var x = horizontal_min;
var y = vertical_min;

enum States { horizontal_plus, vertical_plus, horizontal_minus, vertical_minus }

var state = States.horizontal_plus;

for (i = 1; i <= totalNumbers; i++)
    array[x, y] = i;
    switch (state)
        case horizontal_plus:
            if (x == horizontal_max)
                state = vertical_plus;
        case vertical_plus:
            if (y == vertical_max)
                state = horizontal_minus;
        case horizontal_minus:
            if (x == horizontal_min)
                state = vertical_minus;
        case vertical_minus:
            if (y == vertical_min)
                state = horizontal_plus;

Good luck!

commented Feb 16 by Shahriyor Yuldashev (690 points)
Woo Thank you!
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.