Skip to content

Instantly share code, notes, and snippets.

@wmjd
Last active April 23, 2019 09:57
Show Gist options
  • Save wmjd/78b4c53e2595a2852aadc9c9ddfe986f to your computer and use it in GitHub Desktop.
Save wmjd/78b4c53e2595a2852aadc9c9ddfe986f to your computer and use it in GitHub Desktop.
Randomize array with guaranteed unique in possibly linear time
//version that only works for arrays of nums in JS
var array = [0,1,2,3,4,5,6,7,8,9]
var r, i = array.length
console.log(array)
while (i --> 1) {
r = Math.floor(Math.random()*i);
if(array[r] !== array[i]){
array[r] = array[r] ^ array[i];
array[i] = array[r] ^ array[i];
array[r] = array[r] ^ array[i];
}
}
console.log(array);
//version that works on any object
var a = [{p:1},{p:2},{p:3},{p:4}];
const swap = (i,r) => {
const t = a[i];
a[i] = a[r];
a[r] = t;
}
i = a.length
while(i --> 1){
r = Math.floor(Math.random()*i);
swap(i,r);
}
console.log(a);
//((i) => {while(i --> 1)swap(i, Math.floor(Math.random() * i))})(a.length)
////////////////////////////////////////////////
const shuffle = a => {
const loop = (i) => {
if(i>1){
swap(i -1, rand(i));
loop(i -1);
}
}
const swap = (i,r) => {
const t = a[i];
a[i] = a[r];
a[r] = t;
}
const rand = i => Math.floor(Math.random() * i);
loop(a.length);
}
shuffle(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment