I do not understand what the problem is in this code.

Jordan Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 2 20:14:02 PST 2017


On Friday, 3 March 2017 at 03:11:24 UTC, steven kladitis wrote:
> void main() {
>     import std.stdio, std.range, std.algorithm, std.string;
>
>     const pieces = "KQRrBbNN";
>     alias I = indexOf;
>     auto starts = permutations(pieces.dup).filter!(p =>
>             I(p, 'B') % 2 != I(p, 'b') % 2 && // Bishop 
> constraint.
>             // King constraint.
>             ((I(p, 'r') < I(p, 'K') && I(p, 'K') < I(p, 'R')) ||
>              (I(p, 'R') < I(p, 'K') && I(p, 'K') < I(p, 'r'))))
>         .map!toUpper.array.sort().uniq;
>     writeln(starts.walkLength, "\n", starts.front);
> }

I saw this answer for a similar question from Adam D. Ruppe:
Quote:
"...it is anything that Phobos considers "bidirectional" and 
"swappable" - an array it can reverse easily and swap individual 
elements, and it considers plain string to be non-swappable due 
to UTF-8 encoding. Due to its variable length element encoding, 
swapping two chars may require reshuffling the entire array, 
which would be far more expensive than the function allows.

Thus, the easiest way to make this work is to use a type which 
Phobos considers to be swappable: a UTF-32 string, aka dchar[]."

So, here's my attempt at something that might work for you:
     const pieces = "KQRrBbNN";
     alias I = indexOf;
     auto starts = permutations(pieces.to!(dchar[])).filter!(p =>
             I(p, 'B') % 2 != I(p, 'b') % 2 && // Bishop 
constraint.
             // King constraint.
             ((I(p, 'r') < I(p, 'K') && I(p, 'K') < I(p, 'R')) ||
              (I(p, 'R') < I(p, 'K') && I(p, 'K') < I(p, 'r'))))
         .map!(to!string)
         .map!(toUpper).array.sort().uniq;
         writeln(starts.walkLength, "\n", starts.front);

Note: the ".map!(to!string)" part was just to get round dealing 
with the fact that permutations returns an Index.

It's may not be exactly what you want, but hopefully set you on 
the right track.

Jordan



More information about the Digitalmars-d-learn mailing list