Search code examples
mathlua

(LUA) Generate a unique number from 2 numbers


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


Solution

  • 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