Cleaned up the C++ and implemented a solution in Haskell.