Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number array without duplicates next to each other in Javascript? [duplicate]

I have a function that pushes a sequence of random numbers to an empty array. I don't mind duplicates in the array, but I really need it NOT to repeat numbers that are next to each other. So, for example [1,2,3,4,1] would be totally fine, but [1,1,2,3,4] would not. I've tried putting an if statement into the code, but I'm not quite getting it right. Here's the code I'm using to generate the array. Any help, as always, very gratefully received!

let initArray = [];

function makeCircleArray(level) {
    var i = 0;
  do {
    var val = Math.floor(Math.random() * 9)
    initArray.push(val)
    i++
  }
  while (i < level.dots)
  console.log(`${initArray}`)
  return initArray;
}
like image 804
Maccles Avatar asked Aug 14 '26 07:08

Maccles


1 Answers

You can do this by not inserting the new value if it matches the previously-inserted one:

let initArray = [];

function makeCircleArray(level) {
  var i = 0;
  do {
    var val = Math.floor(Math.random() * 9);
    if (val !== initArray[initArray.length - 1]) {
      initArray.push(val);
      i++;
    }

  } while (i < level.dots);
  console.log(`${initArray}`);
  return initArray;
}

makeCircleArray({ dots: 20 });
like image 86
Daniel Beck Avatar answered Aug 16 '26 20:08

Daniel Beck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!