perfect version with random move