I have code that randomly selects 15 sprites from 51 sprites. It can generate 2 duplicated sprites (this is acceptable for me) but I want to avoid 3 duplicated values. How can I prevent that?
My code
for (int i = 0; i < 16; i++)
{
int arrIndex = UnityEngine.Random.Range(0, tasSprites.Length);
tasSprite = tasSprites[arrIndex];
tasName = tasSprite.name;
taslar.Add(Int32.Parse(tasName));
}
Have you tried checking if each generated index already appears twice in taslar
and if so, generating another one?
while (taslar.Count < 16)
{
int arrIndex = UnityEngine.Random.Range(0, tasSprites.Length);
tasSprite = tasSprites[arrIndex];
tasName = tasSprite.name;
int value = Int32.Parse(tasName);
if (taslar.Count(t => t == value) < 2)
{
taslar.Add(value);
}
}
You could do something like:
int[] indexesCount = new int[tasSprites.Length];
while (taslar.Count < 16)
{
int arrIndex = UnityEngine.Random.Range(0, tasSprites.Length);
if (indexesCount[arrIndex] == 2)
{
continue;
}
indexesCount[arrIndex]++;
tasSprite = tasSprites[arrIndex];
tasName = tasSprite.name;
taslar.Add(Int32.Parse(tasName));
}
Note that this solution is "good" while tasSprites.Length
is relatively small. We are creating a temporary array of size tasSprites.Length
to see which numbers have already been used.
This will save you the chance of possibly repeatedly generating values that have already been used twice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.