Mapping a range of values to another value

纵然是瞬间 提交于 2019-12-05 21:38:01

Since the ranges are consecutive, you can try to map them by the start number, and then find the value with a dichotomic search:

var map = [
    [1, 49],
    [10, 54],
    [25, 59],
    [50, 50],
    [75, 49],
    [100, 40],
    [151, void 0]
];
function getValueInRange(arr, n, from, to) {
    return (function main(from, to){
        if(from>=to) return void 0;
        var mid = Math.floor((from+to)/2);
        if(arr[mid][0] > n) return main(from, mid);
        if(arr[mid][0] < n && mid > from) return main(mid, to);
        return arr[mid][1];
    })(from===void 0 ? 0 : from, to===void 0 ? arr.length : to);
}
// Use it like this:
getValueInRange(map, value);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!