Archive for June, 2010

How the Random Album Chooser Works

I noticed the other day that I had a Google hit from the search term “random albums algorithms” and I realised that I hadn’t explained how the program works. So I thought I’d put together a short blog post to explain it. But first a little background in how I’ve got my music organised.

I have a single folder in which I store all my digital music. This contains folders for each artist. Each artist’s folder then contains folders containing the albums by that artist:

How I've got my music organised

How I’ve got my music organised

I implemented a recursive algorithm which starts at the root (e:\chris\music) and chooses a random folder at each level down the hierarchy until it finds a folder that contains music files (in this case mp3s):

private string Find(string root, string fileType, Random random)
{
    string chosen = null;
 
    // Find all the folders under the root
    string[] folders = Directory.GetDirectories(root);
 
    while (chosen == null)
    {
        if (folders.Length > 0)
        {
            chosen = this.Find(folders[random.Next(0, folders.Length)],
                               fileType, random);
        }
        else
        {
            // No directories in this folder - look for music files
            if (Directory.GetFiles(root, fileType).Length > 0)
            {
                chosen = root;
            }
            else
            {
                // No sub folders and no music files so
                // back up a level to try another folder
                return chosen;
            }
        }
    }
}

This gives an (almost) equal chance for each artist to be chosen and then an equal chance for each album by that artist to be chosen.

If I’d just picked out a folder from the list of albums then it would have meant that those artists with a lot of albums would get chosen more often than those with only one or two, which of course is a perfectly valid approach – if I’ve got a lot of albums by that artist I obviously like them a lot. However, it would mean that the more obscure artists would get chosen less – not something I want.

The other advantage of this algorithm is that it works (almost) regardless of how you’ve got your music organised. If you have albums under a single folder then it will work, if you have folders representing years in there somewhere it will work too. The only time it doesn’t work is if you’ve got all your music files in one folder. But then again, if you’ve got your music “organised” like that, you probably don’t listen to albums any more.

© 2010, Chris. All rights reserved. If you republish this post can you please link back to the original post.

,

No Comments