I can't think of a good algorithm. Perhaps you can help.