值的范围映射到另一个值范围

2023-09-11 23:08:20 作者:余笙我陪你

我试图找到一种有效的方式,一定范围的值映射到另一个值。例如

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  

下面的值不遵循任何规律patters.One解决方案是使用条件语句(如果-else ),但作为一组值增加语句数量增加,这将是很难maintain.So有没有其他的优雅和高效的方式实现这一目标?

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 ?

推荐答案

由于范围是连续的,你可以尝试通过起始号码映射它们,然后找到一个二分查找值:

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