3

I'm struggling with my assignment and need some help.

The program I have to code must traverse (more exactly - fill with natural numbers from 1 to N^2, but the traversal algorithm is what I struggle with) a 2D array A[N][N], where N is odd (1,3,5,7...), starting from center ( A[N/2][N/2] ) and moving spirally and clockwise.

Example (N=5):

25  10  11  12  13
24  9   2   3   14
23  8   1   4   15
22  7   6   5   16
21  20  19  18  17

I see the pattern : center=1 ; 1xUP, 1xRIGHT, 2xDOWN, 2xLEFT, 3xUP, 3xRIGHT, and so on ...

How can I implement this algorithm with loops? Time is ticking away and I'm stuck here ...

Will be happy to read some suggestions and receive help.

Thank you!

Waterfalse
  • 33
  • 1
  • 3
  • Yes, I saw this, but how should I edit the code so it starts from center, going vertically UP and then continuing spirally & clockwise ? That's the struggle. EDIT: I also have a code for spiral & clockwise traversal, starting from indices [0][0] (the beginning of the matrix). I am currently working on it so it traverses from inside-out. I can paste that code here and if possible : give me tips how to rework it. – Waterfalse May 19 '17 at 10:07
  • you can also use square kernel for this (instead circular `cos,sin`) see [Rotate a diagonal line in a 2D 3 x 3 grid - rotation matrix needed?](http://stackoverflow.com/a/40355825/2521214) So just loop squares from center to outer edge of matrix ... similar to rendering concentric circles – Spektre May 19 '17 at 11:21

1 Answers1

0

You can use same implementation and change direction of first step here: Print 2-D Array in clockwise expanding spiral from center

int x = 0; // current position; x
int y = 0; // current position; y
int d = 0; // current direction; 0=RIGHT, 1=DOWN, 2=LEFT, 3=UP
int c = 0; // counter
int s = 1; // chain size

int d - is current direction; change it to 3.

Community
  • 1
  • 1
knst
  • 523
  • 2
  • 16
  • 1
    Thank you, @knst ! I'm doing it this way now and it almost works. Needs some work to make it work correct. Will write here when I'm done! – Waterfalse May 19 '17 at 10:22
  • Well, I made it that way but the only problem left is that the last element from the traversal (element with coordinates [0][0] ) is not reached. For example : N=5, it fills the matrix as desired, but the last element ( matrix[0][0] ) has a random value instead of N^2 = 25. – Waterfalse May 19 '17 at 11:31
  • May I ask what actually these fragments (for's) are doing: for (int k=1; k<=(size-1); k++) { for (int j=0; j<(k<(size-1)?2:3); j++) What are they used exactly for? – Waterfalse May 19 '17 at 14:02