How can I generate an array of random numbers that fluctuate by 1 in javascript?

Viewed 765

I want to be able to generate the following array (or something like it) in 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.
]

How can I do that?

I've tried this, but I always get a random number followed by 1's and -1's only:

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))
4 Answers

This might help:

function randomGenerator(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(randomGenerator(10));
console.log(randomGenerator(13));

or if you prefer to go functional you can take advantage of default values and comma operator:

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

console.log(randGenerator(10))
console.log(randGenerator(13))

Simple solution:

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))

Here is how you can do it with a recursive function, you can set the initial min and max for the random number and also specify the final array length:

const arr = [];

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

function updateArr(min, max, arrLength, arr) {
  if (arrLength) {
    let resultNum = getRandomInt(min, max);
    if (resultNum !== arr[arr.length - 1]) {
      arr.push(resultNum);
      updateArr(resultNum - 1, resultNum + 1, arrLength - 1, arr);
    } else updateArr(min, max, arrLength, arr);
  }
}

updateArr(0, 100, 10, arr);

console.log(arr);

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

Is this working for you?

Related