samedi 1 août 2020

How to shuffle an array without moving FALSY elements?

Here is my attempt; a slightly-modified Fisher-Yates algorithm. I am not sure how to make sure it's random though.

const shuffleWithoutMovingFalsies = array => {
  const newArray = [...array];
  const getRandomValue = (i, N) => ~~(Math.random() * (N - i) + i);
  newArray.forEach((elem, i, arr, j = getRandomValue(i, arr.length)) => arr[i] && arr[j] && ([arr[i], arr[j]] = [arr[j], arr[i]]));
  return newArray;
}

const array = [1, 2, null, 3, null, null, 4, 5, 6, null];

const shuffledArray = shuffleWithoutMovingFalsies(array);

console.log(shuffledArray);

All I did was add arr[i] && arr[j] && as a check to make sure both elements about to be swapped are NOT falsy.




Aucun commentaire:

Enregistrer un commentaire