- Home /
Checking list every time for duplicates
Hello. I already checked in the forum but couldn't find something similar to my problem.. I generate 2 random numbers every time I click a button and I am trying to save those 2 numbers in a list so I can check every time I click the button for duplicates. For example, on the first run I get '5' and '8', after x times I get again this combination '5' and '8' so I want to prevent this.
questionNumbersList.AddRange(new float[] { firstNumber, secondNumber });
for (int i = 0; i < questionNumbersList.Count; i++)
{
Debug.Log("Position " + i + " with list number: " + questionNumbersList[i]);
}
I am not sure how I can check my list for both numbers and see if I already got '5', '8' skip it and generate two new numbers.
Thanks in advance.
I'm not sure I'd use floats for this. Or if you're set on them, I'd at least round them before adding them to a collection to limit the domain space.
After rounding, I'd consider utilizing a Dictionary<float, int> to store the floats you've seen, enter a while loop to check the keys of the Dictionary (Logical ORing the two values, since you seem to want to reject if one or both are in the seen collection) then add the pair that come up after the while loop exits.
The value you add to the $$anonymous$$eyValuePair doesn't really matter, but what does matter is that Dictionaries are faster to search than lists - List.Contains is slower than Dictionary.Contains$$anonymous$$ey
Thank you for your Answer Vicarian. Sorry I am new and I am not sure if I understood this.. Could you please give me an example?
Answer by toddisarockstar · Jan 11, 2019 at 06:48 AM
if you want two floats, Use Vector2. A Vector2 variable is just two floats.
public List<Vector2> used = new List<Vector2>();
public Vector2 UniqueRandom(){
Vector2 r = new Vector2 (0,0);
while(true){
r = new Vector2(Random.Range(0,10),Random.Range(0,10));
if(!used.Contains(r)){break;}
if(used.Count>99){print("Ooops. all Number combos used");break;}}
return r;
}
void Start () {
//these float combos are never the same.
print(UniqueRandom());
print(UniqueRandom());
print(UniqueRandom());
print(UniqueRandom());
print(UniqueRandom());
print(UniqueRandom());
}
im using a while loop to continue picking as long as there is match in the list. careful of while loops though. If for whatever reason the loop is not stopped, it becomes an infinite loop and really really bad things happen. LOL Thats why i put the extra line to break the loop if you run out of possabilitys!
Answer by Pangamini · Jan 11, 2019 at 04:10 PM
You could store them in a HashSet instead of a list (and of course as Vector2). That's exactly what they are for.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers