Search code examples
algorithmspiral

Very interesting program of building pyramid


I have came across this very interesting program of printing numbers in pyramid.

If n = 1 then print the following,

1  2
4  3

if n = 2 then print the following,

1  2  3
8  9  4
7  6  5

if n = 3 then print the following,

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

I can print all these using taking quite a few loops and variables but it looks very specific. You might have noticed that all these pyramid filling starts in one direction until it find path filled. As you might have noticed 1,2,3,4,5,6,7,8,9,10,11,12 filed in outer edges till it finds 1 so after it goes in second row after 12 and prints 13,14 and so on. It prints in spiral mode something like snakes game snakes keep on going until it hits itself.

I would like to know is there any algorithms behind this pyramid generation or its just tricky time consuming pyramid generation program.

Thanks in advance. This is a very interesting challenging program so I kindly request no need of pipeline of down vote :)


Solution

  • I made a small recursive algorithm for your problem.

    public int Determine(int n, int x, int y)
    {
      if (y == 0) return x + 1;         // Top
      if (x == n) return n + y + 1;     // Right
      if (y == n) return 3 * n - x + 1; // Bottom
      if (x == 0) return 4 * n - y + 1; // Left
      return 4 * n + Determine(n - 2, x - 1, y - 1);
    }
    

    You can call it by using a double for loop. x and y start at 0:

    for (int y=0; y<=n; y++) 
      for (int x=0; x<=n; x++) 
        result[x,y] = Determine(n,x,y);