Skip to content

Instantly share code, notes, and snippets.

@rickd-uk
Created February 6, 2022 02:32
Show Gist options
  • Save rickd-uk/d36467cd979910b3279448d03752f4d5 to your computer and use it in GitHub Desktop.
Save rickd-uk/d36467cd979910b3279448d03752f4d5 to your computer and use it in GitHub Desktop.
Random Non-Repeating
#Whenever an item is selected, move it to the back of the array and randomly select from a slice of the original array array.slice(0, -5).
var a = ["Roger", "Russell", "Clyde", "Egbert", "Clare", "Bobbie", "Simon", "Elizabeth", "Ted", "Caroline"];
var chooseName = function () {
var unique = true;
num = Math.floor(Math.random() * a.length - 5);
name = a.splice(num,1);
a.push(name);
}
window.addEventListener("keypress", function (e) {
var keycode = e.keyCode;
if (keycode == 13) {
chooseName();
}
}, false);
#EDIT: This also has the side-effect of not giving whichever variables happen to tail the list the unfair
# disadvantage that they won't be considered in the first N calls. If that's a problem for you, maybe try
# hold a static variable somewhere to keep track of the size of the slice to use and max it out at
#B (in this case, 5). e.g.
var a = ["Roger", "Russell", "Clyde", "Egbert", "Clare", "Bobbie", "Simon", "Elizabeth", "Ted", "Caroline"];
B = 5; //max size of 'cache'
N = 0;
var chooseName = function () {
var unique = true;
num = Math.floor(Math.random() * a.length - N);
N = Math.min(N + 1, B);
name = a.splice(num,1);
a.push(name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment