Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2020-11-29 14:19:29

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))
Questioner
Nathan Chu
Viewed
0
Alan Omar 2020-11-29 23:42:52

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