The Solution of solutions

I am not entirely sure if this is correct, however I think I see what you were trying to do, and I solved it in a more declarative way. It worked! (and it wasn't even slow!)