On 1/28/12 8:21 AM, Jos van Uden wrote:
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);
}

Could you please also compare with code that uses foreach with stdin.byLine()?


Thanks,

Andrei

Reply via email to