Below is a comparison matrix :
val1,val2,val3
val1,1, 5, 4
val2,5, 3, 5
val3,4, 5, 6
What is an efficient method off accessing values in this matrix. So for example val2,val1 returns 5 & val3,val1 returns 4
Here is a possible method signature :
public int getValue(String name1 , String name2){
.....
return value
}
and to call :
getValue(val2 , val1)
which returns 5
A possible solution is to create a map data structure where the key is combination of the val strings :
map.put("val1,val1" , 1);
map.put("val1,val2" , 5);
map.put("val1,val3" , 4);
And then to return the values in method getValue defined above use :
public int getValue(String name1 , String name2){
return map.get(name1+","+name2)
}
Is this a viable solution or is there a more viable option. The matrix in question is of the order 100000 x 100000 dimension
Update1 : the matrix is symmetric
Update2 : the matrix could be sparse in places
Instead of creating one Map structure, I think you should create two: One to hold the row labels and another to hold the column labels:
HashMap<String,Integer> rowMap, colMap;
rowMap = new HashMap<>();
colMap = new HashMap<>();
// Populate the maps with the row and column key-value pairs
public T getValueAt(String row, String col) {
return myMatrix[rowMap.get(row)][rowMap.get(col)];
}
How about an actual matrix to store the data?
// create and fill a matrix of the right dimensions
int[][] matrix = new int[3][3];
// create a map that maps row/col names to indexes
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("val1", 0);
map.put("val2", 1);
map.put("val3", 2);
// the actual method is straightforward
public int getValue(String name1 , String name2) {
int i = map.get(name1);
int j = map.get(name2);
return matrix[i][j];
}
Also, be aware that the expected size of your matrix (100.000 x 100.000) is huge, the memory usage will be the greatest of your concerns, it might be infeasible to create such a big data structure in memory unless the matrix is sparse, in which case a different approach needs to be devised.
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