Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

洗牌算法 -- 随机数 #99

Open
lovelmh13 opened this issue Jul 4, 2021 · 0 comments
Open

洗牌算法 -- 随机数 #99

lovelmh13 opened this issue Jul 4, 2021 · 0 comments

Comments

@lovelmh13
Copy link
Owner

洗牌算法的关键在于每一次把当前的牌插入到一个随机的地方。

这个随机的范围是当前的这张处于 k 位置的牌,一直到第一张牌 [0, k)。

JS 中的取随机数 Math.random 的范围是 [0, 1),我们给 Math.random * k,就可以得到一个 [0, k) 的随机数了。

于是:

function foo () {
  const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

  for (let k = arr.length -1; k >= 0; k--) {
    const num = parseInt(Math.random() * k)
    const temp = arr[k]
    arr[k] = arr[num]
    arr[num] = temp
  }

  console.log(arr)
}

思路在于:

  • 把数组最后一项,取出,和随机值index互换位置。
  • 把数组倒数第二项,出去, 和随机值index互换位置。
  • ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant