How to sort byCodeUnit.permutations.filter(...)
Adam D. Ruppe
destructionator at gmail.com
Tue Jun 12 14:21:48 UTC 2018
On Monday, 11 June 2018 at 04:39:54 UTC, Uknown wrote:
> Why are the strings getting modified?
I'm guessing it reuses a buffer as it iterates.
> "123".byCodeUnit.permutations.writeln;//[123, 213, 312, 132,
> 231, 321]
so here, it switches them, prints, switches, prints, switches,
prints,e tc
> "123".byCodeUnit.permutations.array.writeln;//[123, 123, 123,
> 123, 123, 123]
but here it adds the same pointer to the array over and over so
it all points to the same buffer.
I'm guessing. I don't actually know.
But hmmm... maybe throwing in a .dup would help. Really though, I
personally would forget all the range pipeline stuff and write a
simple loop.
int largest = 0;
foreach(part; "1234567".byCodeUnit.permutations) {
auto asNumber = to!int(part);
if(primes.canFind(asNumber)) {
if(asNumber > largest)
largest = asNumber;
}
}
writeln(largest);
But, writing the simple loop did give me a solution to the
pipeline too: map it to to!int before doing the rest, so you work
with ints instead of with strings and char buffers:
"1234567".byCodeUnit
.permutations
.map!(to!int)
.filter!(a => primes.canFind(a))
.maxElement
that should do it too.
More information about the Digitalmars-d-learn
mailing list