Skip to content

Instantly share code, notes, and snippets.

@trevnorris
Created February 17, 2021 08:34
Show Gist options
  • Save trevnorris/ffce575fc4fc5dbcea69d91bf1b5286b to your computer and use it in GitHub Desktop.
Save trevnorris/ffce575fc4fc5dbcea69d91bf1b5286b to your computer and use it in GitHub Desktop.
// Call this function with the number of levels in the queue.
// It will return the weighted random position.
function getPosition(n) {
return n - tRoot(randomT(n));
}
function triangular(n) {
return n * (n + 1) / 2;
}
function randomT(n) {
return Math.floor(Math.random() * triangular(n));
}
function tRoot(n) {
return Math.floor((Math.sqrt(8 * n + 1) - 1) / 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment