Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping (x,y) to single number value

Tags:

java

algorithm

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).

like image 575
ssss Avatar asked Jan 27 '11 12:01

ssss


3 Answers

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;
like image 111
paxdiablo Avatar answered Nov 04 '22 05:11

paxdiablo


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 ..
..
like image 43
peoro Avatar answered Nov 04 '22 05:11

peoro


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);
like image 2
Joonas Pulakka Avatar answered Nov 04 '22 04:11

Joonas Pulakka