3

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

2 Answers 2

4

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;
    }
}
0
1

(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.

2
  • 2
    I edited @goodvibration's post to use "block.timestamp". Just for the record, you should be able to do this as well! Aug 17, 2021 at 10:12
  • Oh nice, thanks, I wasn't aware! Aug 17, 2021 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.