Cakes solution, not yet working correctly for all input sets