如何生成相邻间隔在指定最小、最大值之间递增的数字序列
实现方案
核心思路
- n个元素的序列共有
n-1个相邻间隔,我们只需要生成从minSpace平滑过渡到maxSpace的间隔序列,再从起始值累加即可得到目标序列 - 间隔的增长曲线可以通过幂函数调整,支持线性、加速、减速三种增长模式,不需要依赖第三方库也可以实现,也可以借助d3的插值能力简化代码
原生JS实现
function computeSerie(n, minSpace, maxSpace, start = 1, exponent = 1) { // 长度小于2直接返回仅包含起始值的数组 if (n < 2) return [start] const gapCount = n - 1 const result = [start] for (let i = 0; i < gapCount; i++) { // 计算当前间隔的归一化位置,取值范围0~1 const t = i / (gapCount - 1) // 用幂函数调整增长曲线 const adjustedT = Math.pow(t, exponent) // 插值得到当前间隔值 const gap = minSpace + adjustedT * (maxSpace - minSpace) // 累加得到下一个序列值,需要整数结果可包裹Math.round处理 const nextVal = result.at(-1) + gap result.push(nextVal) } // 需要整数序列可打开下方注释 // return result.map(Math.round) return result }
参数说明
n:生成序列的长度minSpace:相邻间隔的最小值maxSpace:相邻间隔的最大值start:序列的起始值,默认是1,可自定义调整到任意定义域exponent:增长曲线指数,默认1为线性增长;大于1时间隔加速增长,小于1时间隔减速增长
测试示例
// 示例1 间隔固定为1 computeSerie(5,1,1) // [1, 2, 3, 4, 5] // 示例2 间隔固定为2 computeSerie(5,2,2) // [1, 3, 5, 7, 9] // 示例3 间隔从1加速增长到4(指数为2) computeSerie(5,1,4, 1, 2).map(Math.round) // [1, 2, 3, 6, 10] // 示例4 间隔线性从1增长到6,调整exponent为1.2即可匹配你给出的示例数值 computeSerie(7,1,6) // [1, 2, 4, 7, 11, 16, 22] 匹配你给出的间隔可视化效果
基于d3的简化实现
如果项目已经引入d3,可以直接用d3的scale能力简化插值逻辑:
import { scalePow } from 'd3-scale' function computeSerie(n, minSpace, maxSpace, start = 1, exponent = 1) { if (n < 2) return [start] const gapCount = n - 1 // 直接用d3的幂比例尺实现间隔插值 const gapScale = scalePow() .exponent(exponent) .domain([0, gapCount - 1]) .range([minSpace, maxSpace]) const result = [start] for (let i = 0; i < gapCount; i++) { result.push(result.at(-1) + gapScale(i)) } return result }
内容的提问来源于stack exchange,提问作者marielle
相关产品推荐
相关产品推荐

