Search Unity

How to count number of times a value is in a list

Discussion in 'Scripting' started by LazyGoblinCody, Dec 15, 2017.

  1. LazyGoblinCody

    LazyGoblinCody

    Joined:
    Mar 18, 2015
    Posts:
    66
    I am basically running a simulation about 1000 times and wanting to store the total that the player receives in each run into a list. At the end of the 1000 times, I want to then cycle through the list and figure out how many times each round total is on the list.

    So for example I run a simulation 5 times:

    The list will contain 5 int values ex: 1000, 750, 1100, 750, 1000

    I want to cycle through that list and print out how many times a total shows up.

    "1000 = 2 times"
    "750 = 2 times"
    "1100 = 1 time"

    Hopefully, this is making sense and I appreciate any help!
     
  2. shuskry

    shuskry

    Joined:
    Oct 10, 2015
    Posts:
    462
    use loop to count how many time for each Index :)

    int totalTime =0;

    for(int i = 0; i < list.Lenght; i++)
    {
    totalTime += list [ i ] .times
    }

    EDIT ( not sur to understand your problem ^^)
     
  3. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
    Linq has a GroupBy method and a Count method. You could also use its ToDictionary functionality or just the overload of Count that takes a Predicate<int>.
     
  4. Fido789

    Fido789

    Joined:
    Feb 26, 2013
    Posts:
    343
    Yeah, you can use linq, but it can be slow:

    Code (CSharp):
    1. foreach (var group in list.GroupBy(i=>i))
    2. {
    3.     Debug.Log(string.Format("Item {0}: {1} times", group.Key, group.Count()));
    4. }
     
    metalpulp and shekalo like this.
  5. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
  6. LazyGoblinCody

    LazyGoblinCody

    Joined:
    Mar 18, 2015
    Posts:
    66
    What is so funny?
     
  7. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,997
    It's a non-Unity programming problem. Easy to look up. It's also a standard array example. Make int[] AllScores; going up the the highest possible score. After each run use: AllScores[pointsThisRun]++;.
     
  8. LazyGoblinCody

    LazyGoblinCody

    Joined:
    Mar 18, 2015
    Posts:
    66
    Thanks, this worked out perfect for me!
     
    metalpulp likes this.
  9. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
    The note that linq can be slow juxtaposed with the context set by the original question.