programing

어레이를 셔플하려면 어떻게 해야 하나요?

javaba 2022. 10. 27. 23:35
반응형

어레이를 셔플하려면 어떻게 해야 하나요?

JavaScript의 여러 요소를 다음과 같이 섞고 싶습니다.

[0, 3, 3] -> [3, 0, 3]
[9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6]
[3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]

최신 버전의 Fisher-Yates 셔플알고리즘을 사용합니다.

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015(ES6) 버전

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

단, 2017년 10월 현재 변수를 파괴적인 할당과 스왑하면 상당한 성능 손실이 발생합니다.

사용하다

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

시제품 구현

「」를 사용합니다.Object.defineProperty(이 SO 답변에서 가져온 방법) 이 기능을 어레이의 프로토타입 방법으로 구현할 수도 있습니다.이 기능은 다음과 같은 루프에 표시되지 않습니다.for (i in arr)에, 「 」를 할 수 있습니다arr.shuffle()arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

Fisher-Yates Shuffle(이 사이트에서 수정한 코드)을 사용할 수 있습니다.

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

언급URL : https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array

반응형