Search Unity

Loop being ran too many times

Discussion in 'Scripting' started by AV_Corey, Jul 30, 2018.

  1. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    I have a list of strings that I want to 'stack', for example if there are 2 lines in the array of strings that are "Egg" then it would display as "Egg x2" in a single string. I'm trying to achieve this by putting a for loop inside a for loop.

    For some reason the code below is sometimes returning more than 1 debug message, meaning it is being ran more than once(!?).

    Code (CSharp):
    1. Debug.Log("Stacking Ingredients...");
    2. string path = Application.dataPath + "/Resources/ShoppingList.txt";
    3. string data = System.IO.File.ReadAllText(path);
    4. lines = data.Split("\n"[0]);
    5.  
    6. for (int i = 0; i < lines.Length - 1; i++) //A
    7. {
    8.     for (int x = 0; x < lines.Length - 1; x++) //B (1)
    9.     {
    10.         string a = lines[i];
    11.         string b = lines[x];
    12.         Debug.Log(i + " and " + x);
    13.         Debug.Log("Checking if A (" + a + ") is equal to B (" + b + ")");
    14.  
    15.         if (a == b)
    16.         {
    17.             //Result
    18.         }
    19.     }
    20. }


    I'm clueless as to why the first Debug.Log is being returned once, and the next one is being returned 12 times, any pointers would be great.
     
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    That will be because the line is unique. The for loops will iterate over each number once. Therefore the permutation of 2 and 0 will only occur once (as will the permutation 0 and 2 which is different).

    Presumably Curry Jar appears once in your list and Chickpeas appears 12 times?
     
  3. FlashMuller

    FlashMuller

    Joined:
    Sep 25, 2013
    Posts:
    450
    Try disabling "Collapse" in the console. The first message might only have the number one, as i or x have changed and therefor the message is different and not stacked with the other messages.

    Yeah, what @Doug_B said :)
     
  4. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    An alternative approach would be to use a Dictionary. Something like this:
    Code (CSharp):
    1. var lines = data.Split('\n');
    2. Dictionary<string, int> inventory = new Dictionary<string, int>();
    3.  
    4. foreach (var item in lines)
    5. {
    6.     if (!inventory.ContainsKey(item))
    7.         inventory[item] = 1;
    8.     else
    9.         inventory[item] += 1;
    10. }