Created
March 11, 2013 10:39
-
-
Save IceCreamYou/5133371 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param lo The closest previous input below the current input | |
* @param hi The closest previous input above the current input | |
* @param loPos The position of lo | |
* @param hiPos The position of hi | |
* @param input The current input | |
* @return The optimal position for input | |
*/ | |
function optimalGuess(lo, hi, loPos, hiPos, input) { | |
// Track the best values | |
var maxGapAmount = 0, maxMinGapPerNum = 0, optimalPos = 0; | |
// Test each possible position | |
for (var i = loPos+1; i < hiPos; i++) { | |
// Calculate the gaps | |
var posAbove = hiPos - i - 1, posBelow = i - loPos - 1; | |
var gapAmount = (posAbove ? (hi - input) : 0) + (posBelow ? (input - lo) : 0); | |
var gapPerNumAbove = (posAbove ? (hi - input) / posAbove : 0); | |
var gapPerNumBelow = (posBelow ? (input - lo) / posBelow : 0); | |
var minGapPerNum = Math.min(gapPerNumAbove, gapPerNumBelow); | |
// If we have the same size gap, optimize for the largest minimum gap per number. | |
// In other words we don't want to cram a bunch of numbers into a small gap on one side and have a big gap on the other side. | |
if (maxGapAmount < gapAmount || (maxGapAmount == gapAmount && maxMinGapPerNum < minGapPerNum)) { | |
maxGapAmount = gapAmount; | |
maxMinGapPerNum = minGapPerNum; | |
optimalPos = i; | |
} | |
} | |
return optimalPos; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment