0

How to arrange number sequence in a spiral

I want to write a function that takes a number (n) and outputs a sequence of numbers (1 to n x n) in the form of an n*n grid, with the numbers arranged in a spiral. The starting position is either the center. With an input n=3 and pos = "center" then

results for example:

5  4  3
6  1  2
7  8  9

Or the number sequence starts in one of the corners. With an input n=4 and pos = "top right" the result is for example:

4   3   2   1
5  14  13  12
6  15  16  11
7   8   9  10

Does anyone have an idea how to get a specific position in the grid? And how to arrange the sequence in a spiral instead of entering it column by column or row by row?

  • 2
    what is your expected output incase spiral start from (2,1) index in 4x4 matrix – sahasrara62 Sep 08 '22 at 10:17
  • 1
    @sahasrara62: that's... not a valid starting point, according to the question. – Sergio Tulentsev Sep 08 '22 at 10:21
  • 1
    Does this question help you a bit to get the logic? https://stackoverflow.com/questions/36834505/creating-a-spiral-array-in-python –  Sep 08 '22 at 10:21
  • If the input is n = 4 and pos = 'center', which coordinate do you expect to start from? – Mechanic Pig Sep 08 '22 at 10:22
  • This problem is a good candidate for a recursive solution. That is, you can view these spirals as a sequence of concentric squares. – Sergio Tulentsev Sep 08 '22 at 10:23
  • @SergioTulentsev sorry, you are right, OP has asked position can be corner or center only. my bad understanding the OP statement. But still in this for even gird ie (n is even) what woudl be the output for that if position is center – sahasrara62 Sep 08 '22 at 10:31
  • @sahasrara62: yeah, fair point. I would expect the judge system to accept all four possible outputs in this case. – Sergio Tulentsev Sep 08 '22 at 10:42
  • @SergioTulentsev for center case with odd element, corner coordinate as starting point with anti clock spiral patther it can be done . only with center starting point and even N value, need more info/example output to give the correct solution – sahasrara62 Sep 08 '22 at 10:46

0 Answers0