0

I have a list of type Vector3Int that contains the end location of my agents movement, I want to compare these values to see if they are equal,

pseudo code;

if (2 or more items within the list are the same value) {
  create a new end of path location for one or more of the agents  
}

Thanks in advance for you help

Marmiton
  • 29
  • 2
  • 9
  • What have you tried? How would you do it as a human if I gave you a piece of paper with numbers written on it – BugFinder Oct 06 '20 at 18:07

1 Answers1

1

There are a few ways to do it.

You can run a loop that uses a LINQ query. It would check each item in the list and see if there are more than 1 of that item in the list. LINQ's version of Count() allows you to compare values.

bool HasDuplicates = false;
foreach (var item in MyList) {
    if (MyList.Count(i => i.x == item.x && i.y == item.y) > 1) {
        HasDuplicates = true;
        break;
    }
}

Or you can use Distinct() to make a second list that only has 1 of every value. Then compare the count of both lists. If the distinct one has a lower count, then there must be duplicates in the list.

var HasDuplicates = (MyList.Distinct().Count < MyList.Count)
Thomas Finch
  • 482
  • 2
  • 6
  • The first snippet is very bad performance wise since in worst case you iterate the entire list `n * n + 1` times! The second one only works since luckily the type in question is `Vector3Int` which already implements a proper equality check `return a.x == b.x && a.y == b.y && a.z == b.z;` .. otherwise in general it might happen that `Distinct` checks for reference equality in which case it might fail for some use cases ;) – derHugo Oct 07 '20 at 09:11
  • Precisely why I listed both methods. Second one good for most cases, first one good enough otherwise. Probably some better ways though. – Thomas Finch Oct 08 '20 at 00:21
  • It's def not efficient, but comparing values in a list isn't going to be particularly efficient. – Thomas Finch Oct 08 '20 at 00:29
  • Syntactically it has to be `MyList.Distinct().Count()` instead of `MyList.Distinct().Count`. – beuzel Sep 23 '21 at 09:58