I have been messing around with a script for the past 2 days and I cannot figure this out.
i have an array of string names and I have my script pick random strings and assign them to a set of UI texts. problem is some text have duplicate strings assigned and I need non-duplicate string names assigned. This is a looping coroutine that goes off every 10 minutes, selects from a list of 25 strings and needs to assign string names from the array to the 25 UI texts without any of the text having duplicates. I am very new to using arrays so if someone has a solution a working script would help a lot.
Here is a simple Fisher-Yates shuffle for an array of strings
// Assuming your class has some array of strings
// called stringList
void ShuffeList()
{
string tmp;
for (int i=stringList.Length-1;i >0; i++)
{
int j = Random.Range(0,i);
tmp = stringList[j];
stringList[j] = stringList[i];
stringList[i] = tmp;
}
}
// Then if you can grab strings starting at 0, and they will be random.
// Just shuffle each time before you grab a new set.
Note: if your stringList gets really large, copying strings around can get very expensive versus copying integers. So you can abstract the shuffle to an array of integer indices, and leave your stringList static like this:
string stringList[1000] = new string[1000];
int stringListIndex[1000] = new int[1000];
void Awake()
{
// Code to fill up your stringList would go here
for (int i=0;i<1000;i++)
stringListIndex[i]= i;
}
void ShuffeList()
{
for (int i=stringListIndex.Length-1;i>0;i--)
{
int j = Random.Range(0,i);
int tmp = stringListIndex[j[;
stringListIndex[j] = stringListIndex[i];
stringListIndex[i] = stringListIndex[j];
}
}
// then you just access the strings like this:
string[] smallList = string[10];
for (int i=0;i<10;i++)
smalleList[i] = stringList[stringListIndex[i]];
Thank you so much for the code. This is something that found and it worked for me and is very simmilar to your code but it is called the knuth shuffle algorithm.
Another alternative for non repeating random selection is to remove items from the original collection once they are chosen. Will make sense in some cases.