本文介绍了值的范围映射到另一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到一种有效的方式,一定范围的值映射到另一个值。例如
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);更多推荐
值的范围映射到另一个值
发布评论