提供一个数字 n,生成一组 0~n-1 的整数,打乱顺序组成数组,打乱几次,如何能够看起来平衡,说出你能想到的所有方法。

181 阅读1分钟

使用sort()排序方法

function shuffled_1(n) {
    const arr = Array.from(Array(n).keys());
    arr.sort(() => Math.random() - 0.5);
    return arr;
}

let s1 = shuffled_1(10);
console.log(s1);

使用 Fisher-Yates 洗牌算法


function shuffled_2(n) {
    const arr = Array.from(Array(n).keys());

    for(i = 0; i < n; i++){
        let j = Math.floor(Math.random()*(i+1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}

let s2 = shuffled_2(10);
console.log(s2);

用随机插入法进行打乱顺序

function shuffled_3(n) {
    const arr = Array.from(Array(n).keys());
    const shuffledArr  = [];

    /**
     * 1. 准备一个空数组
     * 2. 从 arr 数据中随机取一个放入 shuffledArr 数组中
     * 3. 直到数组 arr 为空。
     */

    while(arr.length >0 ) {
        const i = Math.floor(Math.random()*( arr.length )); // 注意不要越界
        shuffledArr.push(arr.splice(i, 1)[0]);
    }

    return shuffledArr;
}

let s3 = shuffled_3(10);
console.log(s3);

为了看起来平衡

  1. 可以使用合适的算法,比如用Fisher-Yates洗牌算法。
  2. 对数组进行多次打乱,每次使用不同的打乱算法,增加打乱的随机性。