0

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));
}
Charlie Salts
  • 13,109
  • 7
  • 49
  • 78
cemthecebi
  • 104
  • 13

3 Answers3

5

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);
    }
}
Tudor
  • 61,523
  • 12
  • 102
  • 142
2

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.

xanatos
  • 109,618
  • 12
  • 197
  • 280
1
  • Generate an array with each of your sprites in twice
  • Select 15 values from the array using e.g. a Fisher-Yates shuffle

This will save you the chance of possibly repeatedly generating values that have already been used twice.

Rawling
  • 49,248
  • 7
  • 89
  • 127