1

By looking at this image I think you will understand my problem pretty well:

(image removed - url no longer valid, returns advertising now)

So basically I want a function that takes an object as parameter and gives this object the correct coordinates based on how many objects I've added before.

Let's say I would add all these objects to an array:

objectArray[]

Each time I add a new object: objectArray.add(object)

The object.x and object.y coordinates will be set based on some algorithm:

object.x = ?
object.y = ?

(I'm working in Java)

Thanks for any help.

Brandon
  • 38,310
  • 8
  • 82
  • 87

1 Answers1

7

Here's the closed-form solution that doesn't rely on a loop... I'm not handy with Java, so it's in C#, but it uses basic operations.

static void SpiralCalc(int i) {
    i -= 2;
    // Origin coordinates
    int x = 100, y = 100;
    if (i >= 0) {
        int v = Convert.ToInt32(Math.Truncate(Math.Sqrt(i + .25) - .5));
        int spiralBaseIndex = v * (v + 1);
        int flipFlop = ((v & 1) << 1) - 1;
        int offset = flipFlop * ((v + 1) >> 1);
        x += offset; y += offset;
        int cornerIndex = spiralBaseIndex + (v + 1);
        if (i < cornerIndex) {
            x -= flipFlop * (i - spiralBaseIndex + 1);
        } else {
            x -= flipFlop * (v + 1);
            y -= flipFlop * (i - cornerIndex + 1);
        }
    }
    // x and y are now populated with coordinates
    Console.WriteLine(i + 2 + "\t" + x + "\t" + y);
}
Kaganar
  • 6,540
  • 2
  • 26
  • 59
  • 1
    For a high-performance scenario where you're not accessing the the related objects in a sequential manner, this isn't as bad with some low level optimization on modern processors as you might think -- usually they have a pretty darned good square root approximation that will be as good as you'll practically need with an offset and a truncation. – Kaganar Feb 04 '12 at 00:35
  • FWIW, coordinate rotations (and scalings) can be done cheaply using only the multiplication of complex numbers. This requires only adds and multiplies (no roots or trig are needed). – Raymond Hettinger Feb 04 '12 at 04:59
  • This was exactly what I was looking for. I cannot thank you enough Kaganar! – user1182770 Feb 04 '12 at 11:12