算法-计算范围上的缺口值

Algorithm - Calculating notch values on a range

本文关键字:缺口 范围 计算 算法      更新时间:2023-09-26

给定这些输入:起始,结束,缺口数

start = a number;
end = a larger number;
numberOfNotches = a number; // includes start and end values

如何计算显示范围上的中间值?

,

start = 100;
end = 200;
numberOfNotches = 6; // includes start and end values
输出:

100 ----- 120 ----- 140 ----- 160 ----- 180 ----- 200 

这是目前为止我在JavaScript

中的内容
function getNotchValues(from, to, numberOfNotches){
    var step = Math.floor( ( (to - from) / (numberOfNotches-2) ));
    from = Math.floor(from/step)*step;
    to = Math.ceil(to/step)*step;
    var arr = [];
    for(var i=from; i<=to; i=i+step){
        arr.push(i);
    }
    return arr;
}

这是我到目前为止的逻辑,但它不适合我:http://jsfiddle.net/w8vwG/

看起来像是一个off-by-one/fencepost问题。只要做一个小改动就可以了:

(numberOfNotches-1)

这一行:

var step = Math.floor( ( (to - from) / (numberOfNotches-1) ));
编辑:

我认为这是一个完整的解决方案,在我下面的评论中处理这个问题:

http://jsfiddle.net/RKx87/

function getNotchValues(from, to, numberOfNotches) {
    var step = Math.floor(((to - from) / (numberOfNotches - 1)));
    var arr = [];
    for (var i = from; i <= to; i = i + step) {
        arr.push(i);
    }
    arr[arr.length - 1] = to
    return arr;
}