Search code examples
d

How to check if any element of array in another array?


I have got string aabbccddffgg I need to check if it have at last one element from array: ["bb", "cc"].

What is the best way to do it in D?


Solution

  • find and canFind support a variadic number of needles, so using them is the easiest:

    "aabbccddffgg".canFind("bb", "cc");
    

    Learn more about std.algorithm.searching.canFind here. If you don't know the number of needles at compile-time, it depends a bit on how much you know about the string, but the naive approach would be to loop multiple times over the string:

    auto eles = ["bb", "cc"];
    eles.any!(e => "aabbccddffgg".canFind(e)))
    

    If you know more about the sub elements, there are better approaches. For example, if you know that all needles have all the length n, you could create a sliding window of size n and check whether your needles occur in one of the sliding windows:

    auto eles = ["bb", "cc"];
    "aabbccddffgg".slide(2).canFind!(e => eles.canFind!equal(e));
    

    Learn more about std.range.slide here. The same idea also works in the general case:

    auto eles = ["bb", "cc"];
    string s = "aabbccddffgg";
    s.enumerate
       .map!(e => s.drop(e.index))
       .canFind!(e => eles.canFind!(reverseArgs!startsWith)(e));
    

    Note that drop uses slicing and happens lazily in O(1) without any memory allocation.

    Of course, there are still more efficient approaches with more advanced string matching algorithms.