Skip to content

Instantly share code, notes, and snippets.

@xtremetom
Last active February 27, 2023 22:56
Show Gist options
  • Save xtremetom/cd9798b1f6ca91836ee15f39258e927c to your computer and use it in GitHub Desktop.
Save xtremetom/cd9798b1f6ca91836ee15f39258e927c to your computer and use it in GitHub Desktop.
randomTokenSelector Untested
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
This code is untested, feel free to use it, but do so at your own risk
*/
contract Random {
uint256[] tokens = new uint256[](100);
constructor(){
for(uint256 i; i < 100; i++){
tokens[i] = i;
}
}
function random() public returns (uint256){
require(tokens.length > 0, "Array is empty");
// index of the last value in the tokens array
uint256 lastIndex = tokens.length - 1;
// down to the last array value so we can pop it and we are all done
if(lastIndex == 0){
uint256 tokenId = tokens[0];
tokens.pop();
return tokenId;
}
// pick a random number from 0 to the length of the tokens array
uint256 randIndex = uint256(keccak256(abi.encode(block.timestamp, lastIndex))) % lastIndex;
// use the random number to pull a value from the token array at the randNum index
uint256 tokenId = tokens[randIndex];
if(randIndex == lastIndex){
// if the randNum == last index in tokens, remove the last array value
tokens.pop();
} else {
// randNum was in the middle of the array so we need to do some cleanup
// grab the last value from the array
uint256 lastValue = tokens[lastIndex];
// inject the last value into the at index value of randIndex
tokens[randIndex] = lastValue;
// remove last value from the array
tokens.pop();
}
return tokenId;
}
}
@xtremetom
Copy link
Author

This code is untested, feel free to use it, but do so at your own risk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment