Note that there are some explanatory texts on larger screens.

plurals
  1. POAlgorithm to loop over an array from the middle outwards?
    primarykey
    data
    text
    <p>I'm working on a divide-and-conquer algorithm (in fact, one that does curve fitting to a number of input points). For the 'divide' part, I need to calculate an error term for each point, and if the error exceeds a given threshold, I wish to split the curve at that point and process the left and right sections of the input separately. A simple loop does the trick; but it would be advantageous for me to start at the middle of the current section and work outwards. (To clarify: if I do find a point whose error is too large, I recursively call and generate separate curves for the left and right sections - if all the points are within the threshold, then my curve fits and I return).</p> <p>After a bit of head-scratching, I came up with this (the points are in an array, and the current section is from <code>startIndex</code> to <code>endIndex</code> inclusive):</p> <pre><code>int steps = (endIndex+1-startIndex); int i = (startIndex+endIndex)&gt;&gt;1; int stepdir = 1; for(int q=0; q&lt;steps; q++, i+=stepdir*q, stepdir=-stepdir) { // test point i here and return early if error exceeds threshold } </code></pre> <p>In other words, beginning near the middle, go one index forward, two back, three forward, four back... It works, and I'm sure it's efficient, but it strikes me that there should be a cleaner way to do it, in particular, I ended up having to check the Java language spec to make sure that the statements in the for update expression did evaluate in sequence (even though , is not a sequence operator as it is in C/C++).</p> <p>Any ideas gratefully appreciated. Is there a cleaner way?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload