Reputation: 127
I have two list object like that : A={o1,o2,o3,...on}, B={p1,p2,p3,...pm} (m, n are defined).
I want to store distance among objects from A to B such as : d(o1,p1), d(o1,p2)..., d(o1,pm), d(o2,p1), ...., d(on,pm).
I use a matrix with n rows x m columns to store these distance with rows ordered from o1 to on and columns ordered from p1 to pm
But a problem is that I want to implement a function like that:
public double GetDistance (object obj1, object obj2)
For example, if I call GetDistance(o1, p4) then it will return the value like tis: DistanceMatrix[0][3] = 0.6.
So how can we implement in this case in order to from two objects o1, p4 we can refer that the corresponding row and column in the matrix is 0, 3 (in case I have to use matrix to store distances).
Upvotes: 0
Views: 2056
Reputation: 6284
You can use HashMap<object, Integer> pMap and oMap
, where the keys are the objects, and the value the index of the column or row:
Object[] A = //{o1, o2, o3, o4, ... on};
Object[] B = //{p1, p2, p3, p4, ... pm};
HashMap<Object, Integer> oMap = new HashMap<Object, Integer>();
HashMap<Object, Integer> pMap = new HashMap<Object, Integer>();
for(int i = 0 ; i < A.length ; i++) {
Object o = A[i];
oMap.add(o, i);
}
for(int i = 0 ; i < B.length ; i++) {
Object p = B[i];
pMap.add(p, i);
}
And now you can build you distance matrix, and access the values with:
public double GetDistance (object obj1, object obj2) {
//double[][] d = distanceMatrix;
return d[oMap.get(objt1)][pMap.get(objt2)];
}
Upvotes: 1