How to resolve the algorithm Last letter-first letter step by step in the D programming language
How to resolve the algorithm Last letter-first letter step by step in the D programming language
Table of Contents
Problem Statement
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game.
For example, with "animals" as the category,
Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated.
Extra brownie points for dealing with the full list of 646 names.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Last letter-first letter step by step in the D programming language
Source code in the d programming language
import std.stdio, std.algorithm, std.string;
void trySwap(string[] items, ref string item, in size_t len, ref string[] longest)
pure nothrow @safe {
swap(items[len], item);
search(items, len + 1, longest);
swap(items[len], item);
}
void search(string[] items, in size_t len, ref string[] longest)
pure nothrow @safe {
if (len > longest.length)
longest = items[0 .. len].dup;
immutable lastChar = items[len - 1][$ - 1];
foreach (ref item; items[len .. $])
if (item[0] == lastChar)
trySwap(items, item, len, longest);
}
void main() @safe {
auto pokemon = "audino bagon baltoy banette bidoof braviary
bronzor carracosta charmeleon cresselia croagunk darmanitan deino
emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor
heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus
ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass
petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede
scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly
tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle
whismur wingull yamask".split;
string[] solution;
foreach (ref name; pokemon)
trySwap(pokemon, name, 0, solution);
writefln("%-(%s\n%)", solution);
}
import std.stdio, std.algorithm, std.string, std.array, std.conv;
void search(immutable(char)*[] items, in int len,
ref immutable(char)*[] longest) pure {
if (len > longest.length)
longest = items[0 .. len].dup;
immutable lastChar = items[len - 1][1];
foreach (ref item; items[len .. $])
if (item[0] == lastChar) {
swap(items[len], item);
search(items, len + 1, longest);
swap(items[len], item);
}
}
void main() {
static immutable(char)* prep(in string s) pure {
assert(s.length > 1);
auto sd = s.dup;
swap(sd[1], sd[$ - 1]);
return sd.toStringz;
}
static string unprep(immutable(char)* sd) pure {
auto ms = sd.to!(char[]);
swap(ms[1], ms[$ - 1]);
return ms;
}
auto pokemon = "audino bagon baltoy banette bidoof braviary
bronzor carracosta charmeleon cresselia croagunk darmanitan deino
emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor
heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus
ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass
petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede
scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly
tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle
whismur wingull yamask".split.map!prep.array;
immutable(char)*[] solution;
foreach (ref name; pokemon) {
swap(pokemon[0], name);
search(pokemon, 1, solution);
swap(pokemon[0], name);
}
writefln("%-(%s\n%)", solution.map!unprep);
}
LBB0_4:
movl (%esi), %eax
movb 19(%esp), %cl
cmpb %cl, (%eax)
jne LBB0_6
movl (%edi,%ebx,4), %ecx
movl %eax, (%edi,%ebx,4)
movl %ecx, (%esi)
movl %edi, 8(%esp)
movl 48(%esp), %eax
movl %eax, 4(%esp)
movl 12(%esp), %eax
movl %eax, (%esp)
movl 20(%esp), %eax
calll __D25last_letter_first_letter26searchFNaAPyaxiKAPyaZv
subl $12, %esp
movl (%edi,%ebx,4), %eax
movl (%esi), %ecx
movl %ecx, (%edi,%ebx,4)
movl %eax, (%esi)
LBB0_6:
addl $4, %esi
decl %ebp
jne LBB0_4
import std.stdio, std.algorithm, std.string, std.range, std.typecons;
Tuple!(uint, string[]) findLongestChain(in string[] words)
pure nothrow {
static struct Pair { string word; bool unused; }
uint nSolutions;
void search(Pair[][] sequences, in size_t minHead,
in string currWord, string[] currentPath,
size_t currentPathLen,
ref string[] longestPath) nothrow {
currentPath[currentPathLen] = currWord;
currentPathLen++;
if (currentPathLen == longestPath.length) {
nSolutions++;
} else if (currentPathLen > longestPath.length) {
nSolutions = 1;
longestPath = currentPath[0 .. currentPathLen].dup;
}
// Recursive search.
immutable size_t lastCharIndex = currWord[$ - 1] - minHead;
if (lastCharIndex < sequences.length)
foreach (ref pair; sequences[lastCharIndex])
if (pair.unused) {
pair.unused = false;
search(sequences, minHead, pair.word, currentPath,
currentPathLen, longestPath);
pair.unused = true;
}
}
if (words.empty)
typeof(return)(0, null);
immutable heads = words.map!q{ a[0] }.array;
immutable size_t minHead = reduce!min(heads[0],
heads[1.. $].representation);
immutable size_t maxHead = reduce!max(heads[0],
heads[1.. $].representation);
auto sequences = new Pair[][](maxHead - minHead + 1, 0);
foreach (const word; words)
sequences[word[0] - minHead] ~= Pair(word, true);
auto currentPath = new string[words.length];
string[] longestPath;
// Try each item as possible start.
foreach (seq; sequences)
foreach (ref pair; seq) {
pair.unused = false;
search(sequences, minHead, pair.word,
currentPath, 0, longestPath);
pair.unused = true;
}
return typeof(return)(nSolutions, longestPath);
}
void main() {
auto pokemon = "audino bagon baltoy banette bidoof braviary
bronzor carracosta charmeleon cresselia croagunk darmanitan deino
emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor
heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus
ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass
petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede
scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly
tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle
whismur wingull yamask".toLower.split;
// Remove duplicates.
pokemon.length -= pokemon.sort().uniq.copy(pokemon).length;
const sol = pokemon.findLongestChain;
writeln("Maximum path length: ", sol[1].length);
writeln("Paths of that length: ", sol[0]);
writeln("Example path of that length:");
writefln("%( %-(%s %)\n%)", sol[1].chunks(7));
}
import std.stdio, std.algorithm, std.array, std.typecons,
std.container, std.range;
auto findChain(in string[] seq) pure nothrow /*@safe*/ {
const adj = seq
.map!(item => tuple(item, seq
.filter!(x => x[0] == item[$ - 1])
.array))
.assocArray;
SList!string res;
foreach (immutable item; adj.byKey) {
void inner(in string it, SList!string lst) nothrow {
lst.insertFront(it);
if (lst[].walkLength > res[].walkLength)
res = lst;
foreach (immutable x; adj[it])
if (!lst[].canFind(x))
inner(x, lst);
}
inner(item, SList!string());
}
return res.array.retro;
}
void main() /*@safe*/ {
"audino bagon baltoy banette bidoof braviary
bronzor carracosta charmeleon cresselia croagunk darmanitan deino
emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor
heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus
ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena
porygon2 porygonz registeel relicanth remoraid rufflet sableye
scolipede scrafty seaking sealeo silcoon simisear snivy snorlax
spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix
wailord wartortle whismur wingull yamask".split.findChain.writeln;
}
You may also check:How to resolve the algorithm Polynomial regression step by step in the Ada programming language
You may also check:How to resolve the algorithm Sum and product of an array step by step in the Arturo programming language
You may also check:How to resolve the algorithm Calendar step by step in the Vedit macro language programming language
You may also check:How to resolve the algorithm Abundant, deficient and perfect number classifications step by step in the BCPL programming language
You may also check:How to resolve the algorithm CSV to HTML translation step by step in the Rust programming language