D idom for removing array elements

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 28 03:54:58 PST 2017


On Saturday, 28 January 2017 at 10:46:29 UTC, albert-j wrote:
> On Friday, 27 January 2017 at 08:15:56 UTC, Dukc wrote:
>
>> void main()
>> {   import std.stdio, std.algorithm, std.range, std.array, 
>> std.datetime;
>>     int[] a = [1, 2, 3, 4, 5, 6, 7, 4].cycle.take(2000).array;
>>     int[] b = [3, 4, 6].cycle.take(2000).array;
>>
>>     void originalMethod()
>>     {   auto c = a.remove!(x => b.canFind(x));
>>         assert(c[0 .. 4] == [1, 2, 5, 7]);
>>     }
>>
>>     void WilsonMethod()
>>     {   auto c = a.filter!(x => !b.canFind(x)).array;
>>         assert(c[0 .. 4] == [1, 2, 5, 7]);
>>     }
>>
>>     void myMethod()
>>     {   auto sortedB = sort(b.dup);
>>         auto c = a
>>         .   filter!(i => !sortedB.contains(i))
>>         .   array
>>         ;
>>         assert(c[0 .. 4] == [1, 2, 5, 7]);
>>     }
>>
>>     auto r = benchmark!(originalMethod, WilsonMethod, 
>> myMethod)(1);
>>     foreach(result; r) result.writeln;
>> }
>
>
> How to make it work with std.container.array?

Here is an example:

import std.container.array;
alias ArrI = Array!int;

auto removeAll(ArrI a, ArrI b) {
     import std.array;
     import std.range;
     import std.algorithm;

     auto sortedB = sort(b[]).uniq.array;
     auto c = a[].partition!(v => sortedB.assumeSorted.contains(v),
                           SwapStrategy.stable);
     return ArrI(c);
}

void main() {
     import std.stdio;

     auto a = ArrI(1, 2, 3, 4, 5, 6, 7, 4);
     auto b = ArrI(3, 4, 6);

     a.removeAll(b)[].writeln;
}

Note especially how you slice an Array to access its data.


More information about the Digitalmars-d-learn mailing list