Home > front end >  How to be sure that the next randomly selected value from an array is not the same as the current on
How to be sure that the next randomly selected value from an array is not the same as the current on

Time:12-23

I am randomly selecting values from an array. I want to be sure that the next selected value is not the same as the current one. How can I implement this rule in Javascript?

const pages = [1, 2, 3, 4, 5];
const random = Math.floor(Math.random() * pages.length);
console.log(pages[random]);

This is a result of script. I want to avoid the same values next to each other like in the red circle.

CodePudding user response:

Shuffle the array to guarantee that no number will be repeated:

const pages = [1, 2, 3, 4, 5];

function shuffle(array) {
  let currentIndex = array.length,  randomIndex;
  while (currentIndex != 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
  return array;
}

let shuffled = pages.slice()
shuffle(shuffled)

console.log(shuffled[0]);
console.log(shuffled[1]);

CodePudding user response:

You could filter pages removing current value and only after that select random element.

CodePudding user response:

If the one you pick is the same as the previous one, pick a new one:

const pages = [1, 2, 3, 4, 5];
const random = Math.floor(Math.random() * pages.length);
console.log(pages[random]);

let random2;
// Pick a new one:
while (random == ( random2 = Math.floor(Math.random() * pages.length)));

This assumes every value in the array is different, so it just cares that the two indexes (random and random2) are different.

  • Related