0
\$\begingroup\$

So, I ran into a problem with placing points in a grid while always trying to fit them into a square. Here are some examples (the numbers represent the order of placement):

Placing 1 point:

0

Placing 2 points:

0 1

Placing 3 points:

0 1
2

Placing 7 points:

0 1 4
2 3 6
5

Placing 32 points:

0  1  4  9  16 25
2  3  6  11 18 27
5  7  8  13 20 29
10 12 14 15 22 31
17 19 21 23 24 
26 28 30

Placing 36 points:

0  1  4  9  16 25
2  3  6  11 18 27
5  7  8  13 20 29
10 12 14 15 22 31
17 19 21 23 24 33
26 28 30 32 34 35

I need a way of finding the coordinates of a point from its index. For example:

f(0) = 0, 0
f(1) = 0, 1
f(2) = 1, 0
f(3) = 1, 1
f(4) = 2, 0
f(5) = 0, 2
f(6) = 2, 1
f(7) = 1, 2
f(8) = 2, 2
...
\$\endgroup\$
1

1 Answer 1

0
\$\begingroup\$

You can use something like this:

Vector2Int GetCoordsOfPoint(int n) {
    int side = Mathf.FloorToInt(Mathf.Sqrt(n));

    int square = side*side;

    int difference = n - square;

    if (difference & 1 == 0) {
        return new Vector2Int(side, difference >> 1);
    } else {
        return new Vector2Int(difference >> 1, side);
    }
}

And the other way:

int GetNumberFromCoords(int x, int y) {
    int side = Mathf.Max(x, y);
    int min = x + y - side;

    return side * side + 2 * min + (y > x ? 1 : 0);
}

I've followed the convention of using x to number the columns and y to number the rows, which I think is opposite what you've shown in your last example, but you can exchange x & y if you need the opposite convention.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .