What is the method for creating an array of n points that are equally spaced along a line segment with a length of x?

I recently adapted this function from a Python solution I found on a different platform. Despite the points being evenly spaced, they are not aligned along the center of the line.

The initial point is located at position 0, while the final point is at 83 (with the end of the line segment set at 100).

How can I adjust the alignment of these points to be centered?

To clarify, I want the distance between the first point and 0 to be equivalent to that between the last point and 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 attempted the following adjustment without success:

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 ]

After applying this method, the initial point is now 9 units away from 0, but the last point is only 4 units away from 100.

Answer №1

Update i / count by replacing it with (i + 1) / (count + 1).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Embed images within the JavaScript bundle

Here is my scenario: I have developed a components library for React. Within this library, there is a package bundled with Rollup that contains various assets, including a GIF picture used in one of the components. The specific component utilizing this p ...

The performance of the Ionic app is significantly hindered by lagging issues both on Google

After starting to work with the ionic framework, I noticed a significant change in performance when testing an android app on Chrome for the first time. It was fast and responsive until I added a button that led to a screen with navigation bars, side men ...

What is the process for animating the rotation of my FBX model using the animate function?

I'm trying to figure out how to create a continuous rotation for my FBX model using three.js. Here's what I've attempted so far: Declared my object as a variable Called my object in the animate function for rotation (girl1) However, I enc ...

Modifying the chart width in Chart.js: A step-by-step guide

After creating a chart using Chart Js, I encountered an issue where the chart did not fit within the specified width. Adjusting the attributes of canvas proved to be ineffective, specifically with regards to the width attribute. Despite changing the value, ...

It appears that when importing from a shared package in lerna, the name must include "src" at the end for Typescript or Javascript files

I am currently working on a straightforward lerna project structure as shown below: Project | +-- packages | | | +-- shared | | | | | +-- src | | | | | +-- index.ts | | +-- someDir | | | +-- usesShared | ...

Encountering a Error in Django Channels: WebSocket Connection Unsuccessful

I encountered an issue with the WebSocket connection to 'ws://127.0.0.1:8000/room/ws/tech' failing. I am currently exploring how to develop a real-time Django application using channels and referring to this informative tutorial. During my attem ...

Issue: Sumoselect plugin unable to function properly when interacting with dynamically generated select dropdown

I recently started using the sumoselect plugin, which can be found at . In my project, I have implemented two select dropdowns. The first one is directly added to the HTML page, while the second one is generated dynamically using jQuery. Unfortunately, t ...

Guide to using three.js for applying a texture to an mtl and obj file

I'm attempting to apply a png file onto an mtl/obj file. Prior to mapping However, after mapping, the mtl texture seems to disappear. After mapping What should I do? My English skills are not great. If you have trouble understanding my question, p ...

Sorting Object Values with Alternate Order

Is there a way to sort a JSON response object array in a specific order, especially when dealing with non-English characters like Umlauts? object { item: 1, users: [ {name: "A", age: "23"}, {name: "B", age: "24"}, {name: "Ä", age: "27"} ] ...

Error message indicating that the preflight request failed access control check in Angular 5 with JWT OAuth integration

After spending hours reading through several posts, I have yet to find a solution to a very common problem. It seems that in order for my JavaScript code to access the resource, the server must include the Access-Control-Allow-Origin header in the response ...

Movement and physics mechanics for players using Physi.js

As I work on a basic game using Three.js for rendering and Physijis for physics, my question can be applied to games in general. In games, players often display movement that appears disconnected from the physics engine. They can accelerate instantly and ...

Halt the execution of JavaScript code

I'm having trouble making this conditional if statement work properly... The line " if ( !$section.id == "no-transition" ) " seems to be incorrect. My goal is to prevent JavaScript from executing on sections with the id "no-transition". Could someo ...

jQuery Datatables provide a powerful and customizable way to display

I've been working on a project that requires me to incorporate Grid functionality into the displayed data. To achieve this, I'm utilizing the Datatable plugin from jquery. The implementation is smooth and flawless. However, a concern arises wh ...

The NextJS application briefly displays a restricted route component

I need to ensure that all routes containing 'dashboard' in the URL are protected globally. Currently, when I enter '/dashboard', the components display for about a second before redirecting to /login Is there a way to redirect users to ...

The setInterval function in JavaScript fails to update the result

I have successfully implemented a countdown function that is working as expected. // Set the date we're counting down to var countDownDate = new Date("<?= $stop_datejs ?>"); // Update the count down every 1 second var x ...

What is the best way to invoke a function and dynamically load a section of a view using AJAX?

I want to implement a feature where I can hide one div and load another div using an Ajax function. However, I am facing issues with redirecting to the function as intended. My goal is to load the div without having to refresh the page. <script type="t ...

Utilize Bootstrap to deactivate the time picker feature

I recently downloaded an admin template that includes a datetimepicker. However, I only need the date picker and am struggling to disable the time picker. Can anyone help me fix this issue? I will provide my class file, HTML code, and a snapshot of the tim ...

JavaScript removing elements from an array

In my situation, I am dealing with "scene" and various graphics "objects"... Scene.prototype.objects=new Array(); Scene.prototype.add=function(obj){ var last=this.objects.length; this.objects[last]=obj} Scene.prototype.remove=function(obj){ this.o ...

I am looking to access a public method from a different component in Angular 2

Trying to access the headerExpand property from app.component is causing an error message in the console: metadata_resolver.js:559 Uncaught Error: Invalid providers for "Page1" - only instances of Provider and Type are allowed, got: [?undefined?] page1 ...

Is there a way to automate the loading process when a file is uploaded to an HTML input field?

How can I upload a file via Ajax post in HTML without clicking the button? Currently, my code only works after clicking the bootstrap button. My current implementation is as follows: $(document).ready(function () { $("#but_upload").click(function () { ...