function randomKey(obj) {
var ret;
var c = 0;
for (var key in obj)
if (Math.random() < 1/++c)
ret = key;
return ret;
}
Can someone please explain how this code fairly picks a random key from the object?
function randomKey(obj) {
var ret;
var c = 0;
for (var key in obj)
if (Math.random() < 1/++c)
ret = key;
return ret;
}
Can someone please explain how this code fairly picks a random key from the object?
Say you have three keys in obj. On the first iteration of the loop, 1/++c will be 1, so ret will always be set to the first key. In the second iteration, 1/++c will equal 0.5, so there's a 1/2 probability that the random number generated will be less than that, so a 50% chance that you'll change ret to the second key. On the third iteration 1/++c will be 0.333..., so there will be a 1/3 probability that ret will change to the third key.
For any size collection in obj, you should end up with an even distribution of keys.