Better version of the generation algorithm