I'm in a situation that basically boils down to storing values based on 2 ID's. The ID's are sparse, from different ID pools and pretty much unpredictable so the naive approach is to just store the data in nested hash tables.
The challenge is that these values need to be stored for many sequentially created objects, there are generally only a few values (all though, I have to allow for the possibility of way more) and the performance overhead for creating all the nested hash tables is too much. Rolling my own specialized hash table is unfeasible due to the environment (javascript) so I'm having alternative ideas.
Probably every programmer is familiar with the basic 2d indexing where if you have a 100x100 grid of data, setting for example slot 32x44 would require figuring out its 1D index which would be 44 x 100 + 32 = 4432, simple.
TLDR start here: Now I'm curious if its possible to come up with a 1D index based on a 2D coordinate in a way that doesn't involve limited bounds. In my mind it should be possible, example represented as a lookup table:
my_index[0][0] = 0
my_index[0][1] = 1
my_index[1][0] = 2
my_index[1][1] = 3
my_index[0][2] = 4
my_index[1][2] = 5
my_index[2][0] = 6
my_index[2][1] = 7
my_index[2][2] = 8
...etc
Is there any kind of algorithm that does this? It doesn't have to map them exactly like that of course, could be whatever as long as it creates a unique index out of any 2 inputs. All though the above example would be extra good for my situation as its optimized towards the the two index sets being statistically square which in my case is true.
EDIT: Looking at it, I figured out the forwards function of getting the 1D coordinate just like in my example LUT
it was surprisingly simple, now I gotta figure out the reverse
EDIT 2: Nevermind, figured it out
function t1d(x, y) {
if (x >= y) return x * x + x + y;
else return y * y + x;
}
function t2d(v) {
const a = Math.trunc(Math.sqrt(v));
const b = a * a + a;
if (v >= b) return [a, v - b]
else return [v - a * a, a]
}
That square root is owch for the performance but fortunately in this case, I don't even need to go in reverse!