Sunny-117/js-challenges

洗牌算法

Tsuizen opened this issue · 2 comments

洗牌算法
function shuffle(array) {
  let length = array.length;

  while (length) {
    let random = ~~(Math.random() * length--);
    [array[length], array[random]] = [array[random], array[length]];
  }

  return array;
}
/**
 * 原地打乱数组(洗牌算法)
 */

function shuffle (arr) {
  for (let i = 0; i < arr.length; i++) {
    let j = Math.floor(Math.random() * i);
    [arr[i], arr[j]] = [arr[j], arr[i]]
  }
  return arr
}