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

Fisher-Yates 随机算法 #65

Open
wl05 opened this issue Sep 23, 2019 · 0 comments
Open

Fisher-Yates 随机算法 #65

wl05 opened this issue Sep 23, 2019 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented Sep 23, 2019

  1. 倒序循环这个数组
  2. 取位置范围从0到n的随机数k
  3. k与n 位置的值交换
  4. 直到循环至数组的首个元素
function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const randomIndex = Math.floor(Math.random() * (i + 1));
        [array[i], array[randomIndex]] = [array[randomIndex], array[i]]
    }
    return array;
}

const arr = [1, 2, 3, 4, 5, 6, 7]
const res = shuffle(arr)
console.log(res)
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