三毛笔记

JavaScript数据结构与算法(随机算法)

随机算法

将一个数组中的值进行随机排列,现实中的一个常见场景是洗扑克牌。

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const randomIndex = Math.floor(Math.random() * (i + 1))
    swap(array, i, randomIndex)
  }

  return array
}

function swap(array, a, b) {
  const temp = array[a]
  array[a] = array[b]
  array[b] = temp
}

arr = [1, 2, 3, 4, 5]
console.log(...arr)
console.log(shuffle(arr))

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »