Search code examples
javascriptalgorithmcoordinateslinepoint

How to generate array of n equidistant points along a line segment of length x?


I ported this function from a python answer to a similar question on this site. However, although the points are equidistant from each other, they are not centered on the line.

The first point is at 0 while the last is at 83 (the end of the line segment is 100).

How do I center this row of points?

Specifically, I want the first point to be the same distance from 0 that the last point is from 100.

'use strict';

function generatePoints(count, length) {
  const points = []
  for (let i = 0; i < count; i++) {
    const a = i / count;
    const x = a * length;
    points.push(Math.round(x));
  }
  return points;
}

const points = generatePoints(6, 100);

console.log(points);
// [ 0, 17, 33, 50, 67, 83 ]

I tried this, but it doesn't appear to work as I expected:

for (let i = 0; i < points.length; i++) {
  points[i] += (points[1] / 2);
  points[i] = Math.round(points[i]);
}

console.log(points);
// [ 9, 26, 46, 63, 80, 96 ]

The first point is 9 away from 0, but the last point is 4 away from 100.


Solution

  • Change i / count to (i + 1) / (count + 1).