A
A
AndreyRafalsky132018-12-03 20:24:57
C++ / C#
AndreyRafalsky13, 2018-12-03 20:24:57

How to implement filling a matrix with a spiral through a nested loop?

It is necessary to implement the filling of the matrix with numbers in a spiral

1 2 3 4

12 13 14 5

11 16 15 6

10 9 8 7

Figured out how to implement the filling after 4 cycles. But the question arose of how to simplify the solution. Is it possible to implement filling through two loops, one of which is nested? That is, to simply iterate over the rows and columns. For such a solution, you need to find a pattern between the numerical value and the indices where this value should be located. But I can’t find a pattern in any way, although they said that it definitely exists. Help me figure out if it's possible to implement filling in a similar way.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2018-12-04
@AndreyRafalsky13

It is possible with one cycle:
Works with any rectangular matrices.

I
Ivan Klimenko, 2018-12-05
@yeswell

I remembered how in the tenth grade I solved the same problem. Only in Pascal and myself. Miraculously, the code was preserved, which I will show you, although after the previous answers it does not carry any value.

type tabelo = array[byte,byte] of integer;
procedure filling_spiral(var Q:tabelo; a,b:integer);
  var c,d,e,f,g,h:integer;
  begin
    c:=a-1;
    d:=b-1;
    e:=1;
    if a>=b then f:=b else f:=a;
    for g:=0 to (f div 2) do
      begin
        for h:=b-d+g to d-g do
          begin
            if Q[a-c+g,h]=0 then Q[a-c+g,h]:=e else break;
            inc(e)
          end;
        for h:=a-c+g to c-g do
          begin
            if Q[h,b-g]=0 then Q[h,b-g]:=e else break;
            inc(e)
          end;
        for h:=b-g downto b-d+g+1 do
          begin
            if Q[a-g,h]=0 then Q[a-g,h]:=e else break;
            inc(e)
          end;
        for h:=a-g downto a-c+g do
          begin
            if Q[h,b-d+g]=0 then Q[h,b-d+g]:=e else break;
            inc(e)
          end
      end
  end;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question