Home > OS >  (LUA) Generate a unique number from 2 numbers
(LUA) Generate a unique number from 2 numbers

Time:12-29

I have a grid of tiles each with coordinates such as (-3, 5) or (1, 540) I want to generate a unique seed for each tile but I haven't found a way to do such

CodePudding user response:

You need some kind of "pairing function" - Wiki describes such functions for natural numbers while you need integers including negative ones.

You can enumerate all integer points at coordinate plane in spiral manner

       ^   OY
       |
 16 15 14 13 12
 17  4  3  2 11
 18  5  0  1 10 ==> OX
 19  6  7  8  9
 20 21 22 23 24

So, for example, point -2,-2 has index 20

To calculate such index from coordinates, you can use simple algorithm (details here)

if y * y >= x * x then begin
  p := 4 * y * y - y - x;
  if y < x then
    p := p - 2 * (y - x)
end
else begin
  p := 4 * x * x - y - x;
  if y < x then
    p := p   2 *(y - x)
end;

You don't ask for reverse mapping, but it is definitely possible (layer number is (1 floor(sqrt(p))) / 2 and so on)

To complete: Python function for reverse mapping

def ptoxy(p):
    layer = (int(math.sqrt(p))   1) // 2   # integer division
    topleft = 4*layer*layer
    if p <= topleft:
        if p <= topleft - 2 * layer:
            return [layer, 3*layer    p - topleft]
        else:
            return [-layer   topleft - p, layer]
    else:
        if p >= topleft   2 * layer:
            return [p-topleft - 3*layer, -layer]
        else:
            return [-layer, layer-p   topleft]

and link to quick-made test

CodePudding user response:

If you have a grid of tiles, you may consider that you have a first tile, at the top-left corner and a last tile at the bottom-right corner.

[0] [1] [2]
[3] [4] [5]
[6] [7] [8]

But the [Row:Col] notation is more handy.

[0:0] [0:1] [0:2]
[1:0] [1:1] [1:2]
[2:0] [2:1] [2:2]

So you can access the [Row:Col] element with the formula:

ColunmCount = 3
Element = (Row * ColunmCount)   Col

For example (2:1) offset in your grid will be 2*3 1 which is 7.

[0:0] [0:1] [0:2]
[1:0] [1:1] [1:2]
[2:0] [2:1] [2:2]
      --v--
     2*3 1 = 7

It's simple and each tile will have a unique identifier.

  • Related