Solution to level 39 in Untrusted: http://alex.nisnevich.com/untrusted/