Monday, August 31, 2009

Last Piece Puzzle

So I was away on holiday and I found a puzzle called the Last Piece Puzzle. Basically trying to arrange tetris-like pieces to fill a square with no gaps.

I wrote a program to solve it, which was going to take about thirty years to try every combination. The second attempt found all possible solutions in about 2 minutes.

The difference between the two algorithms is what gets me - it's so subtle. The first algorithm picked a piece and then tried every position on the board for that piece, then once it found a position, it moved on to the next piece. The problem here is that there were often holes left behind that no piece would fit into, so it spent a lot of time trying to solve a board that obviously couldn't be solved.
The second algorithm was only slightly different - instead of trying the pieces in order, try to fill the squares in order. This way there were almost no holes (or the holes were found without too much extra effort) and the algorithm turned out to be hugely faster.

There was a contest to solve it in lisp - the fastest solution there was 0.3 seconds. My second attempt copied the winning algorithm there.

My solution is also floating around.

In total, there are five possible solutions: