Mapping (x, y) to a single numeric value

I want the function to map the value (x, y) to one numeric value and the corresponding inverse mapping in Java.

For example, (2,34) should be mapped to some value of 100, and if we have 100, we should find (2,34).

+3
source share
8 answers

Well, if you have a maximum value for one of them, then yes. Let's say it is ylimited to 0 ... 9999, and then can do:

int num = x * 10000 + y;

(assuming, of course, that the result will correspond to the type - if necessary, you can switch to a wider type, for example long). Then to return:

int x = num / 10000;
int y = num % 10000;
+6
source

(, 100 x (x,y)), n (x,y) : n = x * 100 + y.

- , . , R, R^2 . , , (x,y) n:

1  2  4  7  11 ..
3  5  8  12 ..
6  9  13 ..
10 ..
..
+3

HashMap. - HashMap<Integer, List<Integer>>, , .

+1
public class hash {
public static void main(String args[]) throws IOException
    {
    HashMap<List<Integer>,List<Integer>> g=new HashMap<List<Integer>,List<Integer>>();
    List<Integer> xys=new ArrayList<Integer>();
    List<Integer> ss=new ArrayList<Integer>();
    System.out.println("Enter the coordinates in (x,y)");
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("x");
    int n1=Integer.parseInt(reader.readLine());
    System.out.println("y");

    int n2=Integer.parseInt(reader.readLine());
    xys.add(n1);
    xys.add(n2);
    int d=(int)(Math.pow(xys.get(0),xys.get(1)));

    ss.add(d);

   g.put(xys,ss);
   g.put(ss,xys);
        List<Integer> r= g.get(ss);

        List<Integer> r1=g.get(xys);

        System.out.print("Hash for the value (x,y) mapping");
        System.out.print(r1);


        System.out.print("Hash for the value N, reverse mapping");
        System.out.println(r);


}
}
+1

.

String a = "(2,34)";
String b = "100";

Map<String, String> m = new HashMap<String, String>();
m.put(a, b);
m.put(b, a);

/*print*/
System.out.println(m.get(a));
System.out.println(m.get(b));
0

, paxdiablo, , x y- .

, , .

0

, - . 32- (int), 64- (long). - :

int a = 3;
int b = 4;
long c = ((long) a) << 16 | b;

...

a = (int) (c >> 16);
b = (int) (c & 0xffff);
0

?

If the range of x, y is unlimited, then there is no way to do this in a unique way (so you can always cancel the process).

If the range of numbers is limited, you can do the following: Suppose that x and y are values intin the range from 0 to 99. Then you calculate the result by: z = 100 * x + y. The converse will be: x = z / 100and y = z % 100.

-1
source

Source: https://habr.com/ru/post/1788178/


All Articles