What is the best way to create an array of randomized numbers with a variance of 1 using JavaScript?

I am looking to create an array similar to the following structure using javascript:

[
  52, // random number 0-100
  53, // random +1 or -1
  54, // random +1 or -1
  53, // random +1 or -1
  52, // random +1 or -1
  53, // random +1 or -1
  52, // random +1 or -1
  51, // random +1 or -1
  50, // random +1 or -1
  51, // random +1 or -1
  // etc., etc., etc.
]

Is there a way to achieve this?

I attempted the following approach, but it only generates random numbers followed by alternating 1's and -1's:

Array(50).fill(0).map((v, i, a) => i !== 0 ? (Math.round(Math.random()) ? a[i-1] + 1 : a[i-1] - 1) : Math.floor(Math.random() * 101))

Answer №1

Here is a helpful solution:

function generateRandomArray(size) {
    let result = [];
    let firstValue = Math.round(Math.random() * 100);
    result.push(firstValue);
    
    for (let i=0;i<size-1;i++){
        firstValue += Math.random() > 0.5 ? 1:-1;
        result.push(firstValue)
    }
    return result;
}

console.log(generateRandomArray(10));
console.log(generateRandomArray(13));

If you prefer a functional approach, you can utilize default values and the comma operator:

const generateRandom = (size = 13, init = Math.round(Math.random() *100)) => 
Array(size).fill(0).map(e => (init += Math.random() > 0.5 ? 1:-1, init))

console.log(generateRandom(10))
console.log(generateRandom(13))

Answer №2

Here is a simple solution to generate an array of random numbers with increasing or decreasing values:

function rand(min, max) {
  return min + Math.floor((max + 1 - min) * Math.random())
}

function generate(size) {
  let last = rand(0, 100)
  const array = []
  for (let i = 0; i < size; i++) {
    array.push(last)
    last += rand(0, 1) ? 1 : - 1
  }
  return array
}

console.dir(generate(50))

Answer №3

One way to achieve this is by utilizing a recursive approach. In this method, you can establish the initial minimum and maximum values for generating random numbers, as well as define the desired length of the final array:

const generatedArray = [];

function getRandomInteger(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function populateArray(min, max, requiredLength, arr) {
  if (requiredLength) {
    let randomNumber = getRandomInteger(min, max);
    if (randomNumber !== arr[arr.length - 1]) {
      arr.push(randomNumber);
      populateArray(randomNumber - 1, randomNumber + 1, requiredLength - 1, arr);
    } else populateArray(min, max, requiredLength, arr);
  }
}

populateArray(0, 100, 10, generatedArray);

console.log(generatedArray);

Answer №4

randomNumbers = [Math.random()*100]
for (let i = 0; i < 49; i++){
randomNumbers.push(randomNumbers[i] + (Math.random() > 0.5? 1 : -1))
}

Does this code snippet meet your requirements?

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

What are some tips for using copy and paste with Protractor on a Mac using Chrome?

Is there a way to utilize copy and paste functionality with Protractor on a MAC using Chrome? newInput.sendKeys(protractor.Key.chord(browser.controlKey, "a")); newInput.sendKeys(protractor.Key.chord(browser.controlKey, "c")); newInput.sendKeys(protractor. ...

Creating an Array of Callbacks in TypeScript

How do you define an array of callback functions in TypeScript? Here's how a single callback function looks like: var callback:(param:string)=>void = function(param:string) {}; To declare an array of callbacks, you might try this: var callback: ...

What is the best way to upload this array into the system's memory?

I recently stored an array by using the code below: NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray]; [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"myArray"]; Could you provide the code needed to retrieve this array ba ...

Including files in node package without specifying the name of the dist directory

In my library directory structure for seamless import by node js projects, it looks like this: my-lib/ ├─ dist/ │ ├─ index.js │ ├─ foo.js ├─ src/ │ ├─ index.ts │ ├─ foo.ts ├─ package.json Take a look at my package.j ...

Ensure that the pop-up text triggered by a button click is contained within the same webpage

Allow me to preface my inquiry by mentioning that I possess very minimal coding knowledge, so please bear with any technical terminology inaccuracies. I currently have a webpage featuring various questions, each accompanied by a button below. Upon clickin ...

Discovering the worth of an array property in JavaScript

I have a custom script that generates and outputs a JSON formatted object: function test() { autoscaling.describeAutoScalingGroups(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.lo ...

Transform an object containing key-value pairs into an array of objects that include the key name and its corresponding value

My mind is spinning with this problem... I'm struggling to transform the req.query I receive in Express, which is an object, into an array of objects. I need to pass these to SQL Server as inputs for stored procedures. Here is the data I have - { ...

Leverage PHP arrays and subarrays for creating strings

REVISED During my recent safari on the web, I stumbled upon this intriguing webpage: I came across a different approach to handling arrays (mentioned below) on that site, and the output closely matched what I was aiming for. Surprisingly, I managed to ex ...

Passing a string array from View to Controller using Url.Action in MVC framework

I am facing an issue where I have a method that returns an array (string[]) and I am attempting to pass this array of strings into an Action. However, I am currently unable to pass my parameters as expected. Being new in MVC3, I would appreciate any insi ...

Access information from a service

I have developed a new service named servcises/employees.js: angular.module('dashyAppApp') .service('employees', function () { this.getEmployees = function() { return $.get( '/data/employee.json' ); }; }); ...

Extracting targeted information from a standard object

I faced an issue while trying to convert the result to an array using json_decode(), as I kept getting null. Eventually, I used Service_json() and managed to solve the problem. However, after obtaining the result, I encountered a difficulty in extracting ...

Clicking on an element will remove a class and unselect an input using JQuery

Trying to achieve a functionality where clicking on a list item with a radio button input selects it, but clicking again deselects it. The issue is despite various attempts, nothing seems to work properly. function setupToptions() { if ($('ul.top ...

The return value of fs.mkdirSync is undefined

I'm facing a challenge with creating a directory and utilizing that directory as a variable to extract files from zip/rar files. The section of code that is causing an error is shown below: var fileZip = fileName.replace(/^.*[\\\/]/, ...

acquire information from a variable using angularjs

Given the following variable: var exampleVar = {"id": 0, "Nodeid": 1234, "title":"abc"}; I am looking to retrieve the Nodeid value from the above and save it in a new variable. The desired output should be: var newNodeID = 1234; ...

Column Locking with Merged Rows

I have implemented row spanning in jqgrid by following the instructions provided in this answer: Jqgrid - grouping row level data However, I am facing an issue where setting a column with row span to frozen = true causes the overlay to lose the row spanni ...

Verify your credentials in Geoserver using ASP.NET and IIS

Is it possible to integrate asp.net authentication with openlayers? I have created a Login page for authenticating in openlayers using C# on the server side. Here is an example of my code: Uri uri = new Uri("http://"+username+":"+password+"@localhost:197 ...

Setting Up AdminLTE Using Bower

Recently, I decided to incorporate the Admin LTE Template into my Laravel project. I diligently followed the guidelines outlined here As soon as I entered the command: bower install admin-lte The installation process seemed to start, but then the ...

What is the difference in performance between using named functions versus anonymous functions in Node.js?

Currently, I am working on a Node.js app and was initially using anonymous functions for callbacks. However, after referring to the website callbackhell.com, I discovered that using named functions is considered best practice for coding. Despite switching ...

Reorganize JSON data in JavaScript

I am in the process of creating a tree structure, and I want it to be organized in the order of name, desc, then children. However, the JSON data I have received is not in this order. Is there a way to rearrange it efficiently or perhaps optimize the code ...

What is the best way to correctly render several React components using a single index.js file?

I am facing an issue with rendering two React component classes. One class creates a counter and works fine, while the other class generates a simple string wrapped in HTML tags but does not render. I have tried various tutorials to troubleshoot this probl ...