Last letter-first letter: Difference between revisions

Content added Content deleted
(Small fix in second D program)
(Improved second D version)
Line 91: Line 91:
rufflet trapinch haxorus seaking girafarig gabite exeggcute
rufflet trapinch haxorus seaking girafarig gabite exeggcute
emolga audino</pre>
emolga audino</pre>
Runtime: about 1.23 seconds.
Runtime: about 1.23 seconds, dmd compiler.


This is the same program, with some low-level optimizations:
This is the same program, with some low-level optimizations:
Line 97: Line 97:
std.typecons, std.exception;
std.typecons, std.exception;


struct Ref {
Tuple!(string[], int) findLongestChain(in string[] items) {
static struct Ref {
ushort index;
ushort index;
char lastChar, firstChar;
}
char lastChar, firstChar;

__gshared int nSolutions;
__gshared Ref[] refs, longestPathRefs;

/// tally statistics
void search(in size_t currLen) {
if (currLen == longestPathRefs.length) {
nSolutions++;
} else if (currLen > longestPathRefs.length) {
nSolutions = 1;
longestPathRefs = refs[0 .. currLen].dup;
}
}


// recursive search
const dchar lastChar = refs[currLen - 1].lastChar;
foreach (i; currLen .. refs.length)
if (refs[i].firstChar == lastChar) {
const aux = refs[currLen];
refs[currLen] = refs[i];
refs[i] = aux;
search(currLen + 1);
refs[i] = refs[currLen];
refs[currLen] = aux;
}
}

Tuple!(string[], int) findLongestChain(in string[] items) {
foreach (item; items)
foreach (item; items)
enforce(item.length > 1);
enforce(item.length > 1);


int nSolutions;
Ref[] refs, longestPathRefs;
foreach (ushort i, item; items)
foreach (ushort i, item; items)
refs ~= Ref(i, item[0], item[$-1]);
refs ~= Ref(i, item[0], item[$-1]);

/// tally statistics
void search(in size_t currLen) {
if (currLen == longestPathRefs.length) {
nSolutions++;
} else if (currLen > longestPathRefs.length) {
nSolutions = 1;
longestPathRefs = refs[0 .. currLen].dup;
}

// recursive search
const dchar lastChar = refs[currLen - 1].lastChar;
foreach (i; currLen .. refs.length)
if (refs[i].firstChar == lastChar) {
const aux = refs[currLen];
refs[currLen] = refs[i];
refs[i] = aux;
search(currLen + 1);
refs[i] = refs[currLen];
refs[currLen] = aux;
}
}


// try each item as possible start
// try each item as possible start
Line 171: Line 172:
writeln(" ", sol_nsol[0][i .. min(i+7, $)].join(" "));
writeln(" ", sol_nsol[0][i .. min(i+7, $)].join(" "));
}</lang>
}</lang>
Runtime: about 0.79 seconds.
Runtime: about 0.67 seconds, dmd compiler.


=={{header|Go}}==
=={{header|Go}}==