【问题标题】:Compute a sequence of number whose with fixed min distance and max distance计算具有固定最小距离和最大距离的数字序列
【发布时间】:2021-12-01 02:26:34
【问题描述】:

有没有办法生成n 数字,它们之间的空间会逐渐增长,并且该空间在最小值和最大值之间变化?这些数字的域并不重要。

我想像这样调用一个函数:

const serie = computeSerie(n, minSpace, maxSpace) 

// domain is not important, for example [1, +infinity] but also [0, 1], what you prefer

const serie1 = computeSerie(5, 1, 1) // [1, 2, 3, 4, 5]
const serie2 = computeSerie(5, 2, 2) // [1, 3, 5, 7, 9]
const serie3 = computeSerie(5, 1, 4) // [1, ...] I don't know, I suppose to use a pow math function (?)
const serie4 = computeSerie(7, 1, 6) // [1, 2, 4, 8, 13, 18, 24]

视觉上:

serie1: |-|-|-|-|
serie2: |--|--|--|--|
serie3: |-|???|--| 
serie4: |-|--|---|----|-----|------|

我不知道如何实现这一点,也许 d3 可能有用但如何?

非常感谢您的每一个提示

【问题讨论】:

  • 我不明白你想在这里做什么,但你尝试过使用循环吗?
  • @LeoRamadani 我添加了一个视觉示例和另一个系列,我希望现在更清楚
  • 我认为你根本不需要 d3 来做你正在做的事情。为什么最小空间为 1 和最大空间为 6 会产生这个数组:[1, 2, 4, 8, 13, 18, 24]?什么是增量标准?
  • @Terry 在我的示例中,标准只是 +1。但我不清楚哪种方法是获得具有固定开始和结束距离的增量数字序列之类的最佳方法。从视觉上看,结果应该类似于|-|--|---|----|-----|------|
  • 但是 2 -> 4 不是 +1。 4 -> 8 不是 +1。 13 -> 18 不是 +1... 以此类推。不清楚你在问什么:你需要帮助生成数组,还是帮助可视化它?

标签: javascript math d3.js


【解决方案1】:

这应该可以,但是如果您的 minSpacemaxSpace 值与 n 不匹配,您也会得到小数值。 (可以为那些做一个Math.floor/ceil/round 吗?)

function computeSerie(n, minSpace, maxSpace) {
  const step = (maxSpace - minSpace) / (n - 2)
  const arr = []
  const startAt = 1
  arr.push(startAt)
  for (let i = 1; i < n; i++) {
    arr.push(arr[i - 1] + minSpace + (i - 1) * step)
  }
  return arr
}

console.log(computeSerie(5, 1, 1)) // [1, 2, 3, 4, 5]
console.log(computeSerie(5, 2, 2)) // [1, 3, 5, 7, 9]
console.log(computeSerie(5, 1, 4)) // [1, 2, 4, 7, 11]
console.log(computeSerie(7, 1, 6)) // [1, 2, 4, 7, 11, 16, 22]

// will get fractional values for this
console.log(computeSerie(7, 1, 5)) // [1, 2, 3.8, 6.4, 9.8, 14, 19] 

【讨论】:

    猜你喜欢
    • 2017-11-24
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 2013-02-02
    • 1970-01-01
    • 2021-03-03
    相关资源
    最近更新 更多