How to best translate this C++ algorithm into D?

deadalnix via Digitalmars-d digitalmars-d at puremagic.com
Sat Jun 7 01:27:51 PDT 2014


On Saturday, 7 June 2014 at 03:50:17 UTC, logicchains wrote:
> While my (much more concise; thanks D!) attempt at implementing 
> it is:
>
> forest_t[] meal(in forest_t[] forests) {
>   forest_t[3] possible_meals = [{-1, -1, +1}, {-1, +1, -1}, 
> {+1, -1, -1}];
>   return map!(a => [possible_meals[0]+a, possible_meals[1]+a, 
> possible_meals[2]+a])(forests)
>     .join
>     .filter!(a => !forest_invalid(a)).array
>     .sort.uniq.array;
> }
>

Try

forests.map!(a => only(possible_meals[0]+a, possible_meals[1]+a,
> possible_meals[2]+a))

Also, avoid the use of possible_meals, instead, use the constants 
directly.

>     .filter!(a => !forest_invalid(a)).array

This may ends up doing many allocations. you could use an array 
where you preallocate forests.length * 3 items via the reserve 
function and use it as an output range.

>     .sort.uniq.array;

Same here.

With minor changes, I think you can get major improvement already.


More information about the Digitalmars-d mailing list