Skip to content

Instantly share code, notes, and snippets.

@resilience-me
Created November 8, 2018 19:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save resilience-me/ee78a810d18b645d3cc1fce50e50cea3 to your computer and use it in GitHub Desktop.
Save resilience-me/ee78a810d18b645d3cc1fce50e50cea3 to your computer and use it in GitHub Desktop.
// The shuffle algorithm is similar to Algorithm P (Shuffle) from Knuth, 1969, in turn similar to the Fisher–Yates shuffle
// from 1938. It gets the position of an object from shufflingIndex, using a random number generator, and then updates the
// index so that the same position cannot be given to another object, and does so by switching places between the object
// that was picked, and the first object in the list, exchange shufflingIndex[randomNumber] and shufflingIndex[counter].
struct ShuffleAlgorithm {
mapping(uint => uint) shufflingIndex;
uint counter;
}
ShuffleAlgorithm shuffleUtility;
mapping(address => uint) userID;
uint totalPopulation;
function pickFromHat() {
shuffleUtility.counter++;
entropy = generateRandomNumber(entropy);
uint randomNumber = 1 + (entropy % (totalPopulation - shuffleUtility.counter));
uint randomPosition = shuffleUtility.counter + randomNumber;
if(shuffleUtility.shufflingIndex[randomPosition] == 0) shuffleUtility.shufflingIndex[randomPosition] = randomPosition;
if(shuffleUtility.shufflingIndex[shuffleUtility.counter] == 0) shuffleUtility.shufflingIndex[shuffleUtility.counter] = shuffleUtility.counter;
shuffleUtility.shufflingIndex[randomPosition] = shuffleUtility.shufflingIndex[shuffleUtility.counter];
shuffleUtility.shufflingIndex[shuffleUtility.counter] = shuffleUtility.shufflingIndex[randomPosition];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment