We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
洗牌算法的关键在于每一次把当前的牌插入到一个随机的地方。
这个随机的范围是当前的这张处于 k 位置的牌,一直到第一张牌 [0, k)。
JS 中的取随机数 Math.random 的范围是 [0, 1),我们给 Math.random * k,就可以得到一个 [0, k) 的随机数了。
Math.random
Math.random * 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) }
思路在于:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
洗牌算法的关键在于每一次把当前的牌插入到一个随机的地方。
这个随机的范围是当前的这张处于 k 位置的牌,一直到第一张牌 [0, k)。
JS 中的取随机数
Math.random
的范围是 [0, 1),我们给Math.random * k
,就可以得到一个 [0, k) 的随机数了。于是:
思路在于:
The text was updated successfully, but these errors were encountered: