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
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;
}
}
(answering because I don't have enough reputation to comment yet, but this is a minor side note to @goodvibration's answer) in solidity 0.7.0 the "now" keyword has been depreciated, "block.timestamp" should be used instead.