Improve implementation by reducing the number of rand calls and if-statements.