0

* Disclaimer: I posted this just to save future search time, for anyone *
* who will need this (for some reason) *
Hello! Well, I needed an algorithm to find the offset of a point (relative to the origin)
of a square spiral. I looked quite a bit on the internet but couldn't seem to find
a working solution.

I want a code will generate offsets in the following pattern:
Spiral Pattern

So, for example, if I enter try to get the offset of the index 8, I'll recieve (-1, -1).

  • 2
    When you want to [answer to your own question](http://stackoverflow.com/help/self-answer), try to keep the question and answer separated – jhamon Dec 13 '16 at 14:43
  • @jhamon like this? – theredcoder Dec 13 '16 at 15:09
  • No, in 2 differents posts – jhamon Dec 13 '16 at 16:34
  • @theredcoder you leave question part as you got and move the solution part to Answer (That button down below all posts `Post Your answer`...) – Spektre Dec 14 '16 at 10:18
  • @theredcoder see similar QAs: [Rotate a diagonal line in a 2D 3 x 3 grid - rotation matrix needed?](http://stackoverflow.com/a/40355825/2521214) and [Print 2-D Array in clockwise expanding spiral from center](http://stackoverflow.com/q/33684970/2521214) there are surely more others like these... – Spektre Dec 14 '16 at 10:36

1 Answers1

1

Java:

Vector2D spiral(int i) {
    int index = i + 1;
    int s = ceil(sqrt(index)) + ((ceil(sqrt(index)) % 2 + 1) % 2);
    int ringIndex = 0;
    int p = 1;
    if (s > 1) {
        ringIndex = i - (s - 2) * (s - 2);
        p = s * s - (s - 2) * (s - 2);
    }

    int ri = (ringIndex + (int) (s / 2)) % p;

    int x = 0;
    if (s > 1)
        x = ri < (p / 4) ? ri :
                (ri <= (p / 4 * 2 - 1) ? (p / 4) :
                        (ri <= (p / 4 * 3) ? ((p / 4 * 3) - ri) :
                                0));

    int y = 0;
    if (s > 1)
        y = ri < (p / 4) ? 0 :
                (ri <= (p / 4 * 2 - 1) ? (ri - (p / 4)) :
                        (ri <= (p / 4 * 3) ? (p / 4) :
                                (p - ri)));

    x -= (int) (s / 2);
    y -= (int) (s / 2);

    return new Vector2D(x, y);
}

Python:

def spiral(i):
  index = i+1
  s = math.ceil(math.sqrt(index)) + ((math.ceil(math.sqrt(index)) % 2 + 1) % 2)
  s = int(s)
  ringIndex = 0
  if s > 1:
    ringIndex = i - (s-2)*(s-2)
  p = 1
  if s > 1:
    p = s*s - (s-2)*(s-2)

  ri = (ringIndex + int(s / 2)) % p

  x = 0
  if s > 1:
    x = ri if ri < (p / 4) else \
        ((p / 4) if ri <= (p / 4 * 2 - 1) else
         (((p / 4 * 3) - ri) if ri <= (p / 4 * 3) else
          0))

  y = 0
  if s > 1:
    y = 0 if ri < (p / 4) else \
        (ri - (p / 4) if ri <= (p / 4 * 2 - 1) else
         ((p / 4) if ri <= (p / 4 * 3) else
          (p - ri)))

  x -= int(s / 2)
  y -= int(s / 2)
  return x, y