Creating outward spiral

David Gomes picture David Gomes · Mar 29, 2012 · Viewed 8.7k times · Source

I've been thinking about this and I just can't think of a way to fill in a matrix with an outward spiral, so that I can do the following:

Turn this: 1 2 3 4 5 ... n

To

21 22 23 24 25 26
20 07 08 09 10 27
19 06 01 02 11 28
18 05 04 03 12 29
17 16 15 14 13 30
           ...n

My problem is the algorithm itself, but if instead of pseudocode you can help with C++, that'd be better.

This is some code I wrote to test things out, but I really don't know how I can go about to do this.

#include <stdio.h>
#include <string>

using namespace std;

int main() {
  //int n = 5;
  int spiral[5][6];

  for (int i = 0; i < 5; i++)
    for (int u = 0; u < 6; u++)
      spiral[i][u] = 0;

  spiral[2][2] = 1;
  string direction = "right";
  for (int i = 2; i < 5; i++) {
    for (int u = 2; u < 6; u++) {
      if (direction == "right") {
        spiral[i][u + 1] = spiral[i][u] + 1;
        direction = "down";
      }
    }
  }

  for (int i = 0; i < 5; i++) {
    for (int u = 0; u < 6; u++) {
      printf("%02d ", spiral[i][u]);
    }
    printf("\n");
  }

  return 0;
}

Thank you!

Answer

ipc picture ipc · Mar 29, 2012

You can make the observation that there are similar squares with the lowest value in the bottom-left position then going upwards, right, down and left.

You can use this to create such a function:

template <typename Array>
void spiral_square(Array& a, int x, int y, int side, int& value)
{
  int mx = x+side-1, my=y+side-1;
  for (int i = 1; i <= side-1; ++i) a[my-i][x] = value++;
  for (int i = 1; i <= side-1; ++i) a[y][x+i] = value++;
  for (int i = 1; i <= side-1; ++i) a[y+i][mx] = value++;
  for (int i = 1; i <= side-1; ++i) a[my][mx-i] = value++;
}

See it in action: http://ideone.com/9iL1F