Improve the random algorithm of patterns