Solidity Arrays – Shuffle Array of Integers in Solidity

arrayssolidity

I have an array of integers like this,

uint256[] public numberArr = [0,0,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,4,5,5,5]

What can be the best way to shuffle this array in solidity

Best Answer

Try this:

function shuffle() external {
    for (uint256 i = 0; i < numberArr.length; i++) {
        uint256 n = i + uint256(keccak256(abi.encodePacked(block.timestamp))) % (numberArr.length - i);
        uint256 temp = numberArr[n];
        numberArr[n] = numberArr[i];
        numberArr[i] = temp;
    }
}