Palindromes

Jim Barnett via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 3 16:23:45 PST 2015


On Thursday, 3 December 2015 at 23:42:31 UTC, Nordlöw wrote:
> On Thursday, 3 December 2015 at 21:40:05 UTC, Jim Barnett wrote:
>> Thanks for reading.
>
> My version slightly adjusted version:
>
>
> /** Returns: If range is a palindrome larger than $(D 
> minLength).
>     See also: 
> http://forum.dlang.org/thread/dlfeiszyweafpjiocplf@forum.dlang.org#post-vpzuaqxvtdpzpeuorxdl:40forum.dlang.org
>     See also: 
> https://stackoverflow.com/questions/21849580/equality-operator-in-favour-of-std-range-equal
>     TODO: Test graphemes in `string` and `wstring`.
> */
> bool isSymmetric(R)(R range, size_t minLength = 0) // TODO good 
> value for minLength?
>     if (isBidirectionalRange!(R))
> {
>     static if (isRandomAccessRange!R) // arrays excluding 
> `char[]` and `wchar[]`
>     {
>         if (range.length < minLength) { return false; }
>     }
>     size_t i = 0;
>     while (!range.empty)
>     {
>         import std.range.primitives: front, back, popFront, 
> popBack;
>         if (range.front != range.back) return false;
>         range.popFront(); i++;
>         if (range.empty) break;
>         range.popBack(); i++;
>     }
>     return i >= minLength;
> }
>
> unittest
> {
>     assert(`dallassallad`.isSymmetric);
>     assert(!`ab`.isSymmetric);
>     assert(`a`.isSymmetric);
>     assert(`åäå`.isSymmetric);
>     assert(`áá`.isSymmetric);
>     assert(`åäå`.isSymmetric(3));
>     assert(!`åäå`.isSymmetric(4));
>     assert(``.isSymmetric);
>     assert([1, 2, 2, 1].isSymmetric);
>     assert(![1, 2, 2, 1].isSymmetric(5));
> }
> alias isPalindrome = isSymmetric;

Interesting solution... probably worth some future analysis for 
me...

The `import` statement inside the `for`-loop kind of smells to me.

It's a little more generalized than I was looking for, but 
interesting. Your code is also searching for a threshold of 
symmetry. I haven't encountered a problem like that personally, 
but it's interesting and makes me think.

I appreciate your response.


More information about the Digitalmars-d-learn mailing list