- Home /
How to prevent picking the same combination in array?
Hello,
I have 2 arrays that contain values. Let`s say [1,2,3] and [4,5,6]. I have a function that picks 2 numbers - one from each array and puts them together. Like 1 and 4, 3 and 4, 1 and 6.
The problem is that it can pick the same combination twice and so on. I tried everything I know to prevent it. I need to achieve this: if 1 and 4 have been picked, than It cannot pick them together again. Only 1 and 5, 1 and 6, 2 and 4, 2 and 5, etc.
Is there a specific way to do this or I need to dive deeper into arrays/lists. I can`t seem to find any useful information to solve this, except shuffling and other stuff, that I think don`t achieve what I want.
Thanks for any help.
Answer by navot · Sep 24, 2017 at 12:17 PM
Approach 1: You can create a list that contains every possible combination as a Vector2.
So: {(1,4),(1,5),(1,6),(2,4),...,(3,6)}.
Then you can pick any random element of this list, which will be your combination, and remove it (has to be and not an array because of that), so you will never pick it again.
Approach 2: You could also create a list of Vector2 of all the combinations you already pulled. Every time you pull a new combination, check if that combination is not already in the list, and then add it to the list. Otherwise draw a new combination.
This approach might be more efficient if your arrays are huge and you only need a couple of combinations. Otherwise I would use the first one.
Your answer
Follow this Question
Related Questions
Random texture changer (problem with array) 2 Answers
How to generate unique random number 1 Answer
Pick between two floats 2 Answers
Random select from array and spawn 1 Answer
How to combine Vector3 arrays? 3 Answers