数组乱序 洗牌算法

Posted by CodingWithAlice on November 15, 2024

数组乱序 洗牌算法

从最后一个元素开始从数组中随机选出一个位置交换直到第一个元素
function disorder(arr){
    let cur = arr.length - 1;
    while(cur >= 0) {
        let random = parseInt(Math.random() * arr.length);
        [arr[cur], arr[random]] = [arr[random], arr[cur]];
        cur --;
    }
    return arr;
}
let test = disorder([1,2,3,4,5,6,7]);
console.log('test=', test);

自己写了一个 for循环的

function disorder1(cards) {
    let length = cards.length;
    for (let i = length - 1; i >= 0; i--) {
        let randomIndex = parseInt(Math.random()*length);
        [cards[i], cards[randomIndex]] = [cards[randomIndex], cards[i]];
    }
    return cards
}