reddit daily programmer challenge #1 difficult

My quick and dirty attemp at this reddit daily programming challenge

http://www.reddit.com/r/dailyprogrammer/comments/pii6j/difficult_challenge_1/

It has a bug or two but gets the job done.