added code to solve the assignment

From my tests, it seems to be working fine. However, I'm sure that
it is possible to improve it further.