Shuffled.
Saturday, April 18th, 2020
One of extremely minor side effects of spending more time at home (and we have been spending more time at home) is that our living room TV, which can display pictures from our huge photo library, our Instagram accounts, or old television graphics I’ve created is showing slideshows we’ve created and honed over several years and they’re getting a bit boring.
We call these “screensavers” because they function a lot like the computer screen screensavers—presenting something interesting while keeping the image changing frequently enough that it won’t burn in on the screen.
So I spent a chunk of time updating the script that reads the photos we have on the little 3TB hard drive and then shuffles them and presents them in new and entertaining ways. And because I’m not a particularly good coder, each iteration reveals some silly thing that I had done in the past (“hey, that one picture of Clyde’s Drive-In in St. Ignace showed up three times!”) I was able to tighten it up and make it more allegedly bulletproof.
In order to do this, I had to cobble together javascript code that read the various directories, extract the list of images into an array, and then randomly choose, say, 50 of them to display on the screen.
Oh, did I mention we use a Raspberry Pi hooked up to one of the HDMI ports of the TV to do this? There’s one big clue that this is a hobbyist kind of operation.
But as I was saying, an array that needed to be shuffled. In Javascript.
Hey, Javascript has all kinds of ways to add to, combine, and sort arrays, but there is no native shuffling algorithm. Which led me to learn about the Fisher–Yates shuffle algorithm, also known in the modern form as the Knuth algorithm, or what Knuth himself called “Algorithm P (Shuffling)”. If you’re a human being aware of computers, you probably think that telling a computer to randomly shuffle a collection of things is as simple as asking for just that. Well, no. At least at some level, it has to go down to the methodical process of picking a random element, swapping it with another, and then doing it again, and keeping track of when you’ve done it to all the elements.
This is why I’m glad I’m just a software dilettante. But my hat’s off this afternoon to Fisher, Yates, Knuth, and the people online who published web pages discussing how this works in very, very simple terms.