Shuffling a poker deck in JavaScript with window.crypto.getRandomValues

前端 未结 3 1242
死守一世寂寞
死守一世寂寞 2021-02-05 08:32

A poker deck has 52 cards and thus 52! or roughly 2^226 possible permutations.

Now I want to shuffle such a deck of cards perfectly, with truly

3条回答
  •  太阳男子
    2021-02-05 09:05

    Combining this answer from here with this answer from another question, it seems the following could be a more general and modular (though less optimized) version:

    // Fisher-Yates
    function shuffle(array) {
        var i, j;
    
        for (i = array.length - 1; i > 0; i--) {
            j = randomInt(0, i + 1);
            swap(array, i, j);
        }
    }
    
    // replacement for:
    //     Math.floor(Math.random() * (max - min)) + min
    function randomInt(min, max) {
        var range = max - min;
        var bytesNeeded = Math.ceil(Math.log2(range) / 8);
        var randomBytes = new Uint8Array(bytesNeeded);
        var maximumRange = Math.pow(Math.pow(2, 8), bytesNeeded);
        var extendedRange = Math.floor(maximumRange / range) * range;
        var i, randomInteger;
    
        while (true) {
            window.crypto.getRandomValues(randomBytes);
            randomInteger = 0;
    
            for (i = 0; i < bytesNeeded; i++) {
                randomInteger <<= 8;
                randomInteger += randomBytes[i];
            }
    
            if (randomInteger < extendedRange) {
                randomInteger %= range;
    
                return min + randomInteger;
            }
        }
    }
    
    function swap(array, first, second) {
        var temp;
    
        temp = array[first];
        array[first] = array[second];
        array[second] = temp;
    }
    

提交回复
热议问题