我需要使用玩家拥有的经验值和经验图表来了解玩家的等级。我想以最有效的方式做到这一点。这就是我得到的。注意:真实的 expChart 有数千个级别/索引。所有值都按递增顺序排列。
var expChart = [1,10,23,54,65,78,233,544,7666,22224,64654,456456,1123442];
/*
lvl 0: //0-1[ exp
lvl 1: //[1-10[ exp
lvl 2: //[10-23[ exp
*/
getLvlViaExp = function(exp){
for(var i = 0 ; i < expChart.length ; i++){
if(exp < expChart[i]) break;
}
return i;
}
这是一种更有效的方法。每 x 步(例如 6 步,可能每数百步使用真实图表),我进行快速比较并跳转到近似索引,跳过许多索引。
getLvlViaExp = function(exp){
var start = 0;
if(exp > 233) start = 6;
if(exp > 1123442) start = 12;
for(var i = start ; i < expChart.length ; i++){
if(exp < expChart[i]) break;
}
return i;
}
有没有更好的方法来做到这一点?
解决方案:
Array.prototype.binarySearch = function(value){
var startIndex = 0,
stopIndex = this.length - 1,
middle = Math.floor((stopIndex + startIndex)/2);
if(value < this[0]) return 0;
while(!(value >= this[middle] && value < this[middle+1]) && startIndex < stopIndex){
if (value < this[middle]){
stopIndex = middle - 1;
} else if (value > this[middle]){
startIndex = middle + 1;
}
middle = Math.floor((stopIndex + startIndex)/2);
}
return middle+1;
}