简体   繁体   中英

Random number generator with no more than 2 duplicates

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.

  • Generate an array with each of your sprites in twice
  • Select 15 values from the array using eg a Fisher-Yates shuffle

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM