I'm practicing in Dynamic Programming and I'd like, also, to experiment in Lambda Expressions (to be read "Learn how to code Lambda Expressions").
Let's suppose I'm working on two matrices: MatrixA[][] and MatrixB[][]. I need to check all the cells in MatrixA and incrementally populate them, at the same time populating some entry of the MatrixB.
This is my code:
int[][] A = new int[n][m];
String[][] B = new String[n][m];
for (int i=0; i<=n; ++i)
for(int j=0; j<=m; ++j){
if ( i==0 && j==0 ) A[i][j] = 0;
else if ( i==0 ) A[i][j] = j;
else if ( j==0 ) A[i][j] = i;
else {
if ( A[i-1][j-1] > A[i-1][j] ){
A[i][j] = A[i-1][j-1];
B[i][j] = "D";
} else {
A[i][j] = A[i-1][j];
B[i][j] = "T";
}
}
}
I wonder if there exists some more compact way to code it using Lambda Expressions. Unfortunately, I'm new with Lambdas and I'm not sure this example is suitable for them (or if it's actually convenient to use them here).
I found some solutions that suggest using IntStream, defining the range, and iterating in each element:
IntStream.range(0, n)
.forEach( (i) -> {
IntStream.range(0,m)
.forEach( (j) -> {
// Body of the function.
})
});
But, it seems to be a more complex way to define the for loops.
I'm looking for a way to check the maximum of the two elements (possibly even to check if they're the same, so both are the maximum) and according to which is the max value modifying both Matrices.
Any suggestions?