# Spotify Best-Before challenge

#### Posted on August 25, 2011

##### Last updated on February 10, 2013

Recently while browsing through stackoverflow I found a question regarding the Spotify programming puzzle bestbefore. You can find the problem description here.

Normally I like doing puzzles in Haskell just to train my functional programming brain muscles, but Haskell wasn’t allowed, so I had to do some python.

The gist of the puzzle is, given a date in a format like ‘ab/cd/ef’, find the earliest possible valid date.

I like functional approaches, so my code in python has a functional rather than an imperative feel for it.

I now outline to you my approach to the problem, followed by the code.

The date comes in a format ‘ab/cd/ef’, or possibly some of the fields are prepended by zeros, or the year is actually a full year, like 2012 for example. My process is as follows:

• Generate all the possible permutations of the given input ( there are only 3*2 = 6…). The result is list of tuples in the format (yy,mm,dd).
• Filter the result to only those that pass the validation ( valid year, month, day, check leap year, etc)
• Sort the list
• Take the first element!

And we are done. Very simple, and much cleaner, more functional, than the Java code I saw on stackoveflow. When I have some time, I will redo the problem in Haskell and it will be much cleaner :P

After sending my code to the puzzle robot, was accepted on the first try! :P

Here is the first version of the code, in which I implemented my own permuation method for practice, instead of using the itertools library.

This works perfectly fine, but to make it look prettier, I’ll use the itertools library for permutations and compress the code!