I am porting some Java code to Xojo which doesn't have the same language constructs as Java does.
I have a bug in the port and I think I've narrowed it down to this bit of Java code:
int maxIndex = 0;
int n = vertices.length; // vertices is an array
double max = dot(vertices[0]), candidateMax; // I'm assuming `candidateMax` is being initialised to 0 here.
if (max < (candidateMax = vector.dot(vertices[1]))) {
// Search to the right
do {
max = candidateMax;
maxIndex++;
} while ((maxIndex + 1) < n && max < (candidateMax = vector.dot(vertices[maxIndex + 1])));
} else if ( max < (candidateMax = vector.dot(vertices[n - 1])) ) {
maxIndex = n;
// Search to the left
do {
max = candidateMax;
maxIndex--;
} while (maxIndex > 0 && max <= (candidateMax = vector.dot(vertices[maxIndex - 1])));
}
return maxIndex;
I've ported it to this code (Xojo - more verbose than the code above):
Var maxIndex As Integer = 0
Var n As Integer = Vertices.Count
Var max As Double = vector.Dot(Vertices(0))
Var candidateMax As Double
candidateMax = vector.Dot(Vertices(1))
If max < candidateMax Then
// Search to the right.
Do
max = candidateMax
maxIndex = maxIndex + 1
// Exit?
If maxIndex + 1 >= n Then
Exit
Else
candidateMax = vector.Dot(Vertices(maxIndex + 1))
If max > candidateMax Then Exit
End If
Loop
Else
candidateMax = vector.Dot(Vertices(n - 1))
If max < candidateMax Then
maxIndex = n
// Search to the left.
Do
max = candidateMax
maxIndex = maxIndex - 1
// Exit?
If maxIndex <= 0 Then
Exit
Else
candidateMax = vector.Dot(Vertices(maxIndex - 1))
If max > candidateMax Then Exit
End If
Loop
End If
End If
Return maxIndex
I'm assuming the while
loop conditional:
if (max < (candidateMax = vector.dot(this.vertices[1]))) {
// Search to the right
do {
max = candidateMax;
maxIndex++;
} while ((maxIndex + 1) < n && max < (candidateMax = vector.dot(vertices[maxIndex + 1])));
translates as: "Do the contents of the loop at least once. After each iteration of the loop, check to see if maxIndex + 1
is less than n
. If it's not then exit the loop. If maxIndex + 1
is greater than n
then assign the result of the vector.dot
method to candidateMax
and check to see if max
is less than candidateMax
. If it is then keep iterating".
Is this correct? I think I'm misinterpreting the order that the while
conditional is being evaluated.
I believe you got the loop exit condition wrong.
Original:
while (maxIndex > 0 && max <= (candidateMax = vector.dot(vertices[maxIndex - 1])))
would mean in Xojo, roughly:
...
if maxIndex > 0 then candidateMax = vector.Dot(Vertices(maxIndex - 1))
while (maxIndex > 0) and (max <= candidateMax)
In general, you can translate Java/C's do ... while (b)
into Xojo's do ... loop until not (b)
.
This would mean, in your case:
...
if maxIndex > 0 then candidateMax = vector.Dot(Vertices(maxIndex - 1))
loop until not ( (maxIndex > 0) and (max <= candidateMax) )