completed random-n implemenation