xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js & array & shuffle

js & array & shuffle

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];

list.sort(() => Math.random() - 0.5)
(9) [2, 6, 8, 1, 7, 5, 9, 3, 4]

list.sort(() => Math.random() - 0.5)
(9) [8, 1, 3, 4, 9, 7, 6, 2, 5]

list.sort(() => Math.random() - 0.5)
(9) [9, 8, 5, 7, 6, 1, 3, 2, 4]

list.sort(() => Math.random() - 0.5)
(9) [1, 5, 7, 8, 6, 9, 2, 4, 3]

Array.sort()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

shuffle 洗牌算法

https://zzk.cnblogs.com/my/s/blogpost-p?Keywords=shuffle

https://www.cnblogs.com/xgqfrms/p/11977189.html


function shuffle(arr) {
    let m = arr.length;
    while (m > 1){
        let index = Math.floor(Math.random() * m--);
        [arr[m] , arr[index]] = [arr[index] , arr[m]]
    }
    return arr;
}

refs

https://flaviocopes.com/how-to-shuffle-array-javascript/


©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-06-06 17:47  xgqfrms  阅读(234)  评论(3编辑  收藏  举报