Note that there are some explanatory texts on larger screens.

plurals
  1. POSearching through an unsorted nonuniform pair array for closest entry
    text
    copied!<p>I have an array that looks something like this:</p> <pre><code>[[320, 80], [300, 70], [300, 80], [270, 75], [260, 70], [280, 70]] </code></pre> <p>That is just a snippet, the actual array is 338 big.</p> <p>I am trying to find the next logical element in the array based on some input. So for example I feed in two numbers, I.e. <code>315, 80</code> The next logical one is <code>320, 80</code> if you wanted to find a bigger entry.</p> <p>I don't want to correlate logical to closest because it depends on whether you want a bigger or smaller element. So I suppose by logical I mean "closest in the required direction"</p> <p>As an additional requirement the second number should try and remain as close as possible to the entered value OR the first number should try and remain as close as possible to the original number.</p> <p>I am having issues when it comes to cases such as <code>275, 70</code>, and I want to find the next smallest. That <em>should</em> be <code>260, 70</code> but my implementation keeps picking <code>280, 70</code></p> <p>My current implementation adds the difference between the two numbers and looks for the smallest difference possible. I'm not sure how to enforce a direction.</p> <p><strong>Python Example</strong> (although really I'm looking for a language agnostic solution)</p> <pre><code>elements = [ [320, 80], [300, 70], [300, 80], [270, 75], [260, 70], [280, 70] ] target = [275, 70] bestMatch = [] bestDifference = 0 for e in elements: currentDifference = abs((target[0] - e[0]) - (target[1] - e[1])) if not bestMatch or currentDifference &lt; bestDifference: bestMatch = e bestDifference = currentDifference print bestMatch </code></pre>
 

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