What’s the best way to generate 5 random non duplicating integers from 0 – 20?
I’m thinking, use Math.random with floor, loop it 5 times, check for duplicates, if duplicate, random again.
What’s your way?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Edit: A better solution that this or the others posted here can be found in this answer to this question when it was asked back in 2008. Summarizing: Generate an array (as Darin suggests in his answer below) and shuffle it using the Knuth-Yates-Fisher shuffle. Don’t use a naive shuffle, use one that’s known to have good results.
That’s pretty much how I’d do it, yes. I’d probably use an object to keep track of the integers I already had, since that’s convenient. E.g.:
Then once you’ve created a new random number, check it and possibly keep it: