Find indexes of elements matching a given value in an array

bearophile bearophileHUGS at lycos.com
Sun Sep 9 18:07:53 PDT 2012


Samuele Carcagno:

> I would like to find the indexes of all the elements of an 
> array matching a certain value. I could simply loop over all 
> the elements to do the job, but I was hoping for some ready 
> made function that also works across different types (ints, 
> floats etc...).

I have written you some code, but it's not tested, it works with 
just arrays, items inside the struct is const and this causes 
some troubles, etc.

Writing good library code requires a lot of work. Writing it 
quickly is dangerous.


import std.stdio;

struct FindAllIndexes(T) {
     const T[] items;
     T x;
     private size_t _front;

     this(in T[] items_, T x_) pure nothrow {
         this.items = items_;
         this.x = x_;
         for ( ; _front < items_.length; _front++)
             if (x_ == items[_front])
                 break;
     }

     @property bool empty() const pure nothrow {
         return _front >= items.length;
     }

     @property size_t front() const pure nothrow {
         return _front;
     }

     void popFront() pure nothrow {
         _front++;
         for ( ; _front < items.length; _front++)
             if (x == items[_front])
                 break;
     }
}

FindAllIndexes!T findAllIndexes(T)(in T[] items, T x) {
     return typeof(return)(items, x);
}

void main() {
     const data = [1, 5, 7, 9, 5, 10, 3, 5];
     writeln(data.findAllIndexes(5));
}


A slower higher level version:


import std.stdio, std.algorithm, std.range;

auto findAllIndexes(R, T)(in R items, T x) {
     return iota(size_t.max)
            .zip(items)
            .filter!(p => p[1] == x)()
            .map!q{a[0]}();
}

void main() {
     const data = [1, 5, 7, 9, 5, 10, 3, 5];
     writeln(data.findAllIndexes(5));
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list