Estimated Reading Time: 1 min
Ever wonder how Windows XP chose which picture to use as a logon picture? Some attributed it to the name (and some claimed it chose one due to their ethnicity), others just by random. Well, yes, it’s completely by random. And, it is a simple algorithm that does it. Raymond Chen gives you a look at how it’s done and how it has some safeguards to not completely crash the system if someone adds way too many pictures.
The function uses a one-pass random selection algorithm. I can immediately think of two benefits of this decision. First, compared to the naïve two-pass algorithm of counting up all the items, then randomly picking a number from 1 to n, and then iterating a second time to find the item at that index, it’s more efficient because it reduces the amount of calls into the file system, which is where the bottleneck is. Furthermore, the one-pass algorithm avoids complications if the number of files in the directory changes while the code is running.
MSTechPages is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com. As an Amazon Associate, we earn from qualifying purchases at no extra cost to you.