3
\$\begingroup\$

I have an algorithm and the idea is to move over an array choosing as index the index of the neighboring cell that has the max value.
I.e.

if array[i + 1][j + 1] has the largest value among the 3 then move there.

enter image description here

I have 2 versions of this, but I think it can be cleaner.

version 1:

int maxI = i + 1; 
int maxJ = j + 1; 
if(array[i + 1][j] > array[maxI][maxJ]){ 
 maxI = i + 1; 
 maxJ = j; 
} 
if(array[i][j + 1] > array[maxI][maxJ]){ 
 maxI = i; 
 maxJ = j + 1; 
}
i = maxI; 
j = maxJ; 

version 2:

if(LCS[i + 1][j + 1] > LCS[i][j + 1] && LCS[i + 1][j + 1] > LCS[i + 1][j]){ 
 i++; 
 j++; 
} 
else{ 
 if(LCS[i][j + 1] > LCS[i + 1][j]){ 
 j++; 
 } 
 else{i++;} 
} 

Both versions occur in a while loop which I omitted for clarity.
How can these versions become better?

asked Jan 26, 2013 at 11:35
\$\endgroup\$
1
  • 1
    \$\begingroup\$ In Version 1 you can remove the line ` maxI = i + 1; ` in the first if-block, because it does not do anything. \$\endgroup\$ Commented Jan 26, 2013 at 21:14

1 Answer 1

2
\$\begingroup\$

I think it's easier to follow the second version. I've extracted out some helper variables:

 final int b = array[i][j + 1];
 final int c = array[i + 1][j];
 final int d = array[i + 1][j + 1];
 if (d > b && d > c) {
 i = i + 1;
 j = j + 1;
 } else if (b > c) {
 j = j + 1;
 } else {
 i = i + 1;
 }

It seems a little bit readable for me but to be honest I'm not completely satisfied with the result.

answered Jan 28, 2013 at 6:48
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.