0

I am trying to make code that gives me a random variable from a list of strings, but I do not want it to give me a variable I already got.

Here some code for u my dude ↓↓↓

    public Text[] elements;
    public string[] variables;

    void Start()
    {
        for (int i = 0; i < elements.Length; i++)
        {
            elements[i].text = variables[Random.Range(0, variables.Length)];           
        }
    }
leonheess
  • 16,068
  • 14
  • 77
  • 112
  • Put the numbers in a list. Random one number between 0 and size of list. Then remove that number from the list – Ali Kanat Jan 16 '20 at 16:02
  • 3
    The way to go is actually simply shuffle the list, then go through them one by one, see duplicate links – derHugo Jan 16 '20 at 16:15

3 Answers3

3

You could use a list and remove an item once you've used it

public List<string> variables = new List<string>();
public Text[] elements;

void Start()
{
    for (int i = 0; i < elements.Length; i++)
    {
        string s = variables[Random.Range(0, variables.Count - 1)];
        elements[i].text = s;
        variables.Remove(s);
    }
}
Simon Newman
  • 61
  • 11
1

Without creating new data structure, you can do:

public Text[] elements;
public string[] variables;

void Start()
{

    for (int i = 0; i < elements.Length; i++)
    {
        string randomVariable;

        do {
           randomVariable = variables[Random.Range(0, variables.Length)];
        } while (Arrays.asList(elements).contains(randomString));

        elements[i].text = randomVariable;           
    }
}
Maffe
  • 430
  • 6
  • 14
0

You can try this by creating list of possible numbers, and remove the numbers once you find from the list-

public Text[] elements;
public string[] variables;

void Start()
{
    Random rndom = new Random();
    List<int> possible = Enumerable.Range(0, variables.Length).ToList();

    for (int i = 0; i < elements.Length; i++)
    {  
        int index = rndom.Next(0, possible.Count);
        elements[i].text = variables[possible[index]];
        Console.WriteLine(possible[index]);
        possible.RemoveAt(index);               
     }
}

Output

2
1
0
3
Krishna Varma
  • 4,238
  • 2
  • 10
  • 25