Palindromes
Jim Barnett via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Dec 3 13:40:05 PST 2015
TL;DR I couldn't figure out how to write `isPalindrome` in terms
of std.algorithm.mutation.reverse
I have dabbled in D a few times over the past few years, but
still pretty inexperienced. I decided to work on some project
euler problems in D for fun. A problem requires detecting a
palindrome. I solved this problem in C++ before with this:
bool is_palindrome(const string& str)
{
return str == string(str.rbegin(), str.rend());
}
I found Andrei's response to a stackoverflow question here:
http://stackoverflow.com/questions/14469612/template-conflict-for-palindrome-algorithm-on-string-array
In his response, he suggests this:
bool isPalindrome(Range)(Range r)
{
while (!r.empty) {
if (a.front != a.back) {
return false;
}
r.popFront();
if (r.empty) {
return true;
}
r.popBack();
}
return true;
}
I recognize it's more efficient in terms of CPU time and memory
than my C++ solution, but I suspect there is a shorter expression
to detect palindromes if efficiency isn't the primary concern. So
I am interested in seeing implementations of `isPalindrome` that
utilize `std.algorithm.mutation.reverse`, or anyone who cares to
enlighten me why that might be a misguided thing to want. Thanks
for reading.
More information about the Digitalmars-d-learn
mailing list