Improved random algorithm