java - How to implement 2D list? -
i have matrix having r
rows , c
columns. have store matrix in 2-d array. see figure below.
i find minimum number in each row. if minimum number lies in first column add minimum listc1.
consider above figure.
in first row r1 minimum number 2
, lies in column c1 want add 2 in listc1
. in second row r2 minimum number 4
, lies in column c3 want add 4 in listc3
. in third row r3 minimum number 5
, lies in column c2 want add 5 in listc2
. in nutshell if minimum number lies in first column add minimum number in first list listc1
, if minimum number lies in second column add minimum number in second list listc2
, if minimum number lies in third column add minimum number in third list listc3
, on , forth.
now issue facing how create list of list implement above logic. have developed code (see below) not working properly. please me in regard
note: ther number of columns may vary 3 30 final float[][] matrix = { {2f, 8f, 5f}, {9f, 7f, 4f}, {8f, 5f, 6f}, {7f, 3f, 9f}, {1f, 5f, 5f}, {8f, 7f, 5f}, }; map<integer, arraylist<float>> minsmap = new linkedhashmap<>(); for(int row=0; row < matrix.length; row++) { float min = float.max_value; int mc = 0; for(int col=0; col < matrix[row].length; col++) { if(matrix[row][col] < min) { min = matrix[row][col]; mc = col; } arraylist<float> minlist = minsmap.get(mc); if(minlist == null) { minlist = new arraylist<>(); minsmap.put(mc, minlist); } minlist.add(min); } } for(java.util.map.entry<integer, arraylist<float>> e : minsmap.entryset()) { system.out.println("min values in column " + e.getkey() + ": " + e.getvalue()); }
nestedgroup
initialized once used columns. not correct, need nested group each column.
take @ code, uses map
holding lists of minimum values.
private final static float[][] matrix = { {2f, 8f, 5f}, {9f, 7f, 4f}, {8f, 5f, 6f}, {7f, 3f, 9f}, {1f, 5f, 5f}, {8f, 7f, 5f}, }; @test public void minofmatrixcolumn() { map<integer, list<float>> minsmap = new linkedhashmap<>(); for(int r = 0; r < matrix.length; r++) { float min = float.max_value; int mc = 0; for(int c = 0; c < matrix[r].length; c++) { if(matrix[r][c] < min) { min = matrix[r][c]; mc = c; } } list<float> minlist = minsmap.get(mc); if(minlist == null) { minlist = new arraylist<>(); minsmap.put(mc, minlist); } minlist.add(min); } for(entry<integer, list<float>> e : minsmap.entryset()) { system.out.println("min values in column " + e.getkey() + ": " + e.getvalue()); } }
output
min values in column 0: [2.0, 1.0] min values in column 2: [4.0, 5.0] min values in column 1: [5.0, 3.0]
note lists not ordered column index.
Comments
Post a Comment