I want a function to map the (x,y) value to a single number value and corresponding reverse mapping in Java.
For example (2,34) should map to some value 100 and if we have 100 we should be able to find (2,34).
Well, if you have a maximum value for one of them, then yes. Say y
is limited to 0...9999, then could can do:
int num = x * 10000 + y;
(assuming of course that the result will fit in the type - you can possibly upgrade to a wider type like long
if necessary). Then, to go back:
int x = num / 10000;
int y = num % 10000;
If you've got an upper limit (say 100
is the higher for x
in (x,y)
), then you could associate any n
to a pair of values (x,y)
with this function: n = x * 100 + y
.
If you don't have any limit things get more difficult. A way to associate a number belonging to R
, to a number of R^2
is that of enumerating diagonals. Look at this example, it's a matrix where the (x,y)
cell contains the n
associated to it:
1 2 4 7 11 ..
3 5 8 12 ..
6 9 13 ..
10 ..
..
Remember, primitive numbers are just a bunch of raw bits. If your numbers are 32-bit integers (int
), you could conveniently pack two of them into one 64-bit integer (long
). Something like this:
int a = 3;
int b = 4;
long c = ((long) a) << 16 | b;
...
a = (int) (c >> 16);
b = (int) (c & 0xffff);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With