Home > Blockchain >  Compute a sequence of number whose with fixed min distance and max distance
Compute a sequence of number whose with fixed min distance and max distance

Time:10-13

Is there a way to generate n numbers whose space between them grows incrementally and which that space varies between a min value and a max value? It's not important the domain of these numbers.

I immagine to call a function like this:

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]

Visually:

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

I've no idea how to implement this, maybe d3 could be useful but how?

Thank a lot for every tip

CodePudding user response:

This should work, but if your minSpace and maxSpace values don't match up with n you will get fractional values too. (Can do a Math.floor/ceil/round for those?)

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] 

  • Related