简体   繁体   中英

Conversion from 2D to 1D array

So I'm working on converting this logic from a 2D application to function in a 1D array. The thing that is mostly confusing to me is the arrays and how their looping will function. Any input would be appreciated!

 LcgRandom rand = new LcgRandom(); int[][] triangle = new int[ROWS][]; for (int i = 0; i < triangle.length; i++) { triangle[i] = new int[i + 1]; //System.out.println(triangle[i]); for (int j = 0; j <= i; j++) triangle[i][j] = rand.next(); //System.out.println(triangle[i]); } //Calculate row sums int[][] rowSums = new int[triangle.length][]; for (int i = 0; i < rowSums.length; i++) { rowSums[i] = new int[triangle[i].length + 1]; rowSums[i][0] = 0; for (int j = 0; j <= i; j++) rowSums[i][j + 1] = rowSums[i][j] + triangle[i][j]; } //find the smallest triangle long minSum = 0; for (int i = 0; i < triangle.length; i++) { for (int j = 0; j < triangle[i].length; j++) { long curSum = 0; for (int k = i; k < triangle.length; k++) { curSum += rowSums[k][k - i + 1 + j] - rowSums[k][j]; if (minSum>curSum) minSum=curSum; System.out.println(minSum); } } } return Long.toString(minSum); } 

If you intend to store your 2D array in row major form ie you store all row1 elements first, then row2 elements and so on linearly, then you need to adjust your index calculation.

Assuming your 2D array has R rows and C columns, each row has C elements. Thus your indexes are calculated as :

array_1d[j + i*C] == array_2d[i][j] // This is true.

Hence your 1D array will have R * C elements in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM