lundi 21 décembre 2020

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;
}



Aucun commentaire:

Enregistrer un commentaire