Ad
  • Custom User Avatar

    This is perfect ;(

  • Default User Avatar

    return a.Any(b.Contains);

    if array is null it doesn't work

  • Custom User Avatar

    Yes, definitely simpler. Not sure about more performant...maybe.

  • Default User Avatar

    Perhaps then a.Intersect(b).Any() - even simpler and more performant

  • Default User Avatar

    @amandakleeen Intersect enumerates the source; in a.Intersect(b) all of b is added to a set in a loop, then all of a is removed from that set in another loop. If the removal succeeds the item from a is returned. The removal loop is a yielding operation, meaning that as soon as an intersecting element is encountered (set.Remove returns true) it is returned etc. so it would be slightly more efficient to ask for Any() rather than Count(). This is because Any will quit enumerating the intersection as soon as it discovers there to be one item. Count will count all of them (fully enumerate), which is unnecessary if all we seek is to know if there is at least 1. Side note (which you've done) - there are differences in memory too; because b is turned into a hashset against which a is compared, on a system with more CPU than memory resource it may be better to make b the smaller of the two arrays

  • Default User Avatar

    @phil-port under the hood, this approach could require a lot of comparisons, upto a.Length * b.Length.

  • Default User Avatar

    c# - I tried solvning this using Distinct(), but i get this error, "src/Solution.cs(8,28): error CS1061: 'IEnumerable' does not contain a definition for 'Distinct' and no accessible extension method 'Distinct' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?)". I get en issue trying to use ToArray() too. However it works when i do it in VS, does anybody else get this issue?