Mapping a range of values to another value

a 夏天 提交于 2020-01-13 14:01:06

问题


I'm trying to find a efficient way to map a range of values to another value.For example

1-9 -> 49  
10-24 ->54  
25-49 -> 59  
50-74 -> 50  
75-99 -> 49  
100-150 -> 40  

Here the values don't follow any regular patters.One solution is to use conditional statements ( if -else) but as the set of values increase the number of statements increase and it will be hard to maintain.So is there any other elegant and efficient way to achieve this ?


回答1:


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);


来源:https://stackoverflow.com/questions/22577888/mapping-a-range-of-values-to-another-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!