improvement to algorithm based on Patrick Collison's feedback