值的范围映射到另一个值

编程入门 行业动态 更新时间:2024-10-10 05:27:16
本文介绍了值的范围映射到另一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

值的范围映射到另一个值

本文发布于:2023-11-25 21:10:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631361.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!