How to resolve the algorithm Semordnilap step by step in the D programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Semordnilap step by step in the D programming language
Table of Contents
Problem Statement
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal
This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as lager and regal, should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.)
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Semordnilap step by step in the D programming language
Source code in the d programming language
void main() {
import std.stdio, std.file, std.string, std.algorithm;
bool[string] seenWords;
size_t pairCount = 0;
foreach (const word; "unixdict.txt".readText.toLower.splitter) {
//const drow = word.dup.reverse();
auto drow = word.dup;
drow.reverse();
if (drow in seenWords) {
if (pairCount++ < 5)
writeln(word, " ", drow);
} else
seenWords[word] = true;
}
writeln("\nSemordnilap pairs: ", pairCount);
}
void main() {
import std.stdio, std.file, std.algorithm, std.string, std.range;
auto words = "unixdict.txt".readText.split.zip(0.repeat).assocArray;
auto pairs = zip(words.byKey, words.byKey.map!(w => w.dup.reverse))
.filter!(wr => wr[0] < wr[1] && wr[1] in words)
.zip(0.repeat).assocArray;
writeln(pairs.length, "\n", pairs.byKey.take(5));
}
You may also check:How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Action! programming language
You may also check:How to resolve the algorithm Animate a pendulum step by step in the Amazing Hopper programming language
You may also check:How to resolve the algorithm Magnanimous numbers step by step in the Haskell programming language
You may also check:How to resolve the algorithm Stack step by step in the Sather programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Crystal programming language