On 28-1-2012 14:57, Mantis wrote:
28.01.2012 15:31, Jos van Uden пишет:
import std.stdio, std.stream, std.string, std.range;

void main() {
int countPalindromes;
auto infile = new BufferedFile("unixdict.txt");
foreach (char[] line; infile) {
if (line.walkLength > 1) {
line.toLowerInPlace;
if (line == line.dup.reverse)
countPalindromes++;
}
}
writeln("palindromes found: ", countPalindromes);
}

The same may be done without memory duplication by changing comparison
to this (equal function is in std.algorithm):

if (equal(line, retro(line)))

Hard to say without profiling if it will have actual impact on
performance, but at least it should be more GC-friendly.


Good idea.

It's also faster. I tried with a larger file (ukacd17.txt) which
has 240,000 entries.

---

import std.stdio, std.stream, std.string, std.range, std.algorithm;

void main() {
    int countPalindromes;
    auto infile = new BufferedFile("unixdict.txt");
    foreach (char[] line; infile) {
        if (line.walkLength > 1) {
            line.toLowerInPlace;
            if (equal(line, retro(line)))
                countPalindromes++;
        }
    }
    writeln("palindromes found: ", countPalindromes);
}

Reply via email to