- Home /
Randomly instantiate objects from array without choosing the same item twice.
Hi.
How would I do if I wanted to spawn 5 random objects from an array, without the same object get's chosen twice?
I'm trying to make a "find the pair" game where you need to find the 2 objects that look the same.
I already have some code that removes all other objects spawned last time, and creates a new set of items and makes 2 of the same kind, but unfortunately sometimes there are more pairs...
this is called "shuffling". it's an absolute basic of computer science that if you want to choose from a set with "no repeats", that's a shuffle
Oh, I see. I didn't know the word for it and had trouble finding some example for it. But if the array I'm accessing contains 100 objects and I only need 10 or so, would it also work?
Answer by Talidos · Mar 16, 2014 at 02:09 AM
I did this for an iOS game a while back. The process I ended up following was this:
Create a second array you don't mind removing pieces of, and fill it with all the cards in your deck. This includes duplicates.
Every time you need a new card, pick a random one from the new array and REMOVE IT AFTERWARDS.
Repeat step 2 until the array is empty, and you don't need any more cards.
Sorry I don't have any code for reference, but hopefully this will still help.
Answer by swalex · Mar 16, 2014 at 01:58 AM
Don't use a plain array, but try to use a System.Collections.Generic.List
instead. Fill it with your items just as you do this with your array, and simply remove the items from this list when you pick them.