Some time ago Raymond Chen mentioned that Windows XP chose a new account's picture at random from the files in %ALLUSERSPROFILE%\Application Data\Microsoft\User Account Pictures\Default Pictures. Readers wanted to know which RNG stood behind that choice, and Chen has now delivered the answer on The Old New Thing.

selectRandomFromIterator
selectRandomFromIterator(iterator)
{
  var count = 0;
  var winner = null;
  while (iterator.moveNext()) {
    ++count;
    if (uniform_random(min: 1, max: count) == count) {
      winner = iterator.current();
    }
  }
  return winner;
}

The random number generator is RtlRandomEx, seeded with the current value of GetTickCount(). That seed is fine for picking a default picture, not for any security-sensitive purpose.

The selection itself uses a one-pass algorithm: the special case of reservoir sampling with k equal to 1. The code keeps a running count and replaces the current winner with the nth item with probability 1/n. Chen gives two reasons for this design. It makes fewer file system calls than the naive count-then-pick approach, which matters because the file system is the bottleneck. It also stays correct even if files appear or vanish in the directory while the loop is running.

One final guard: the loop stops after sampling 100 pictures. This protects against pathological behavior if someone fills Default Pictures with a million files.