Shuffle an array in-place using Fisher–Yates shuffle
var shuffle = function(a,b,c){for(b=a.length;b;c=0|b*Math.random(),a[c]=[a[--b],a[b]=a[c]][0]);}
var a = [1, 2, 3, 4, 5, 6, 7];
shuffle(a); console.log(a);
// [2, 3, 6, 7, 4, 1, 5]
shuffle(a); console.log(a);
// [3, 6, 5, 2, 1, 4, 7]
@mattpass will donate 3 Euro to charity for each character golfed away from this function. We found a solution worth
7881 Euro (thanks to tsaniel and p01) but I'm not sure if usingsort
is acceptable. What do you think?This works perfectly for all kinds of arrays but is about 5 times slower than the original Fisher–Yates implementation.
Edit: About being original. Come on. I'm sure this was done a million times before. Nevertheless, I came up with the idea myself without using Google.