3

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;
}
Maccles
  • 131
  • 8

2 Answers2

4

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 });
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
  • You need a special case for the first value, also you cannot increment the loop as when a duplicate is found otherwise you will get too few elements in the resulting array. Kudos for providing running code. You are a better man than me :-) – Allan Wind Dec 21 '20 at 20:26
  • The first value doesn't need a special case (it ends up comparing against `undefined`, which works out fine.) I corrected the problem with incrementing `i` too often; thanks for pointing that out! – Daniel Beck Dec 21 '20 at 20:30
  • Rolled back an edit which removed explanatory text and added insignificant changes to the code. Please don't do that @baymax – Daniel Beck Dec 21 '20 at 20:36
1

Keep the last value, and repeat the loop if you get the same value:

var last_val = null;
do {
  var val = Math.floor(Math.random() * 9);
  if(val == last_val) continue;
  initArray.push(val);  
  i++;
  last_val = val;
 } while(i < level.dots)
Allan Wind
  • 23,068
  • 5
  • 28
  • 38