Basically I pick a random number between 0-24:
Math.floor(Math.random() * myArray.length); // myArray contains 25 items
Lets say it comes out to be 8. Now I want to get another number in the same range 0-24 but this time, I do not want an 8. The next time, I might roll a 15. Now I want to roll again but I don't want an 8 or 15. The way I am handling this now is by using do while loops and if the number comes out the same, I just reroll.
This is a small portion of my homework and I, in fact, have it working to meet all the requirements so I guess you could say this is for my own personal benefit so I can write this properly and not end up on "the daily wtf".
This is easy guys. You do not want recursion for this one. These answers are really bad. Ideally you do not want to hardcode the array, either.
now use the value returned from the above function to choose an element from whatever array you want, just like so:
that's it. if you wanted to exclude more than value, then you would have to make this more sophisticated, but for excluding one value, this works well. A recursive solution for this is overkill and a bad idea.
I haven't tested this, but to exclude more than one element, try this:
The above method does not sound too different from the OP's original method. This method works properly because it does not sample in a biased way from the array.
step 1> create an array CHECK_ARRAY fill the array with value which is out of the range of your random number [fill it with 26 if you want to generate number within 0-25]
step2-> generate a random number and add it to RANDOM_ARRAY and also add it to the CHECK_ARRAY that is
step3-> generate a new random number and go though the CHECK_ARRAY, if you found 26 then ignore, else if you found duplicate then re-generate a random number and continue step 3 again until you found an unique random number !
Hmz :-? Fastest way to randomly get items from an array and ensure they're all unique would be:
Suppose you need to choose a random number from the range
1...5
and exclude the values2, 4
then:1...3
Set an array with all the values (this is only a valid option if you're only doing small numbers, like the 25 in your example), like this:
then, pick a random number between 0 and the array length:
remove that index number from the array:
Javascript splice() removes indexed items from an array and returns the item(s) as an array. Perfect for your use.
Grab the first index from the roll, since we only cut 1 out anyway:
Keep doing for as many rolls as you want. Also, you might want to store the original array as a copy so that you can "reset" the numbers easily.