Semordnilap: Difference between revisions

22,064 bytes added ,  1 month ago
m
m (→‎{{header|PHP}}: Fix link: Perl 6 --> Raku)
 
(46 intermediate revisions by 29 users not shown)
Line 1:
{{task}}
 
A [[wphttps://en.wiktionary.org/wiki/semordnilap|#Noun semordnilap]] is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
"Semordnilap" is a word that itself is a semordnilap.
 
Example: ''lager'' and ''regal''
<br><br>
;Task
This task does not consider semordnilap phrases, only single words.
Using only words from <u>[http://wiki.puzzlers.org/pub/wordlists/unixdict.txt this list]</u>, report the total number of unique semordnilap pairs, and print 5 examples. (Note that lager/regal and regal/lager should be counted as one unique pair.)
Using only words from <u>[http://wiki.puzzlers.org/pub/wordlists/unixdict.txt this list]</u>, report the total number of unique semordnilap pairs, and print 5 examples.
<br><br>
Two matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.
;Related tasks
(Note that the word "semordnilap" is not in the above dictionary.)
* [[Palindrome_detection|Palindrome detection]]
 
 
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V wordset = Set(File(‘unixdict.txt’).read().split("\n"))
V revlist = wordset.map(word -> reversed(word))
V pairs = Set(zip(wordset, revlist).filter((wrd, rev) -> wrd < rev & rev C :wordset))
 
print(pairs.len)
print(sorted(Array(pairs), key' p -> (p[0].len, p))[(len)-5..])</syntaxhighlight>
 
{{out}}
<pre>
158
[(damon, nomad), (lager, regal), (leper, repel), (lever, revel), (kramer, remark)]
</pre>
 
=={{header|8th}}==
We're using a map to keep track of what's been seen, and an array to store the results. We load the "unixdict.txt" as an "asset", meaning a file stored alongside the program code:
<syntaxhighlight lang="forth">
<lang Forth>
[] var, results
 
Line 33 ⟶ 51:
a:shuffle
( a:shift dup . " is the reverse of " . s:rev . cr ) 5 times bye
</syntaxhighlight>
</lang>
 
{{out}}
Line 49 ⟶ 67:
Before tackling the real problem, we specify a package String_Vectors and a class String_Vectors.Vec, to store the list of words in the dictionary:
 
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;
 
package String_Vectors is
Line 67 ⟶ 85:
-- checks if Word is in List(Start .. Stop);
-- requirement: the words in List are sorted alphabetically
end String_Vectors;</langsyntaxhighlight>
 
The specified class String_Vectors.Vec has been derived from Ada.Containers.Indefinite_Vectors.Vector and provides two additional primitive operations Read and Is_In. Here is the implementation:
 
<langsyntaxhighlight Adalang="ada">package body String_Vectors is
 
function Is_In(List: Vec;
Line 105 ⟶ 123:
end Read;
 
end String_Vectors;</langsyntaxhighlight>
 
This is the main program:
 
<langsyntaxhighlight Adalang="ada">with String_Vectors, Ada.Text_IO, Ada.Command_Line;
 
procedure Semordnilap is
Line 138 ⟶ 156:
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("pairs found:" & Integer'Image(Semi_Counter));
end Semordnilap;</langsyntaxhighlight>
 
{{out}}
Line 151 ⟶ 169:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer p, z;
record r;
file f;
Line 171 ⟶ 189:
}
 
o_form("Semordnilap pairs: ~\n", p);</langsyntaxhighlight>
{{out}}
<pre>ca ac
Line 183 ⟶ 201:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
The Algol 68 G "read" PRAGMA is used to include the associative array code from Associative_array/Iteration.
<langsyntaxhighlight lang="algol68"># find the semordnilaps in a list of words #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
Line 244 ⟶ 262:
close( input file );
print( ( whole( semordnilap count, 0 ), " semordnilaps found", newline ) )
FI</langsyntaxhighlight>
{{out}}
<pre>
Line 254 ⟶ 272:
158 semordnilaps found
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">words: read.lines "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
pairs: []
loop words 'wrd [
if and? contains? words reverse wrd
wrd <> reverse wrd [
'pairs ++ @[@[wrd reverse wrd]]
print [wrd "-" reverse wrd]
]
]
 
unique 'pairs
 
print map 1..5 => [sample pairs]</syntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">S := [], M := []
 
FileRead, dict, unixdict.txt
Line 278 ⟶ 311:
r := A_LoopField . r
return r
}</langsyntaxhighlight>
{{out}}
<pre>5 Examples:
Line 291 ⟶ 324:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SEMORDNILAP.AWK unixdict.txt
{ arr[$0]++ }
Line 312 ⟶ 345:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 325 ⟶ 358:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Line 374 ⟶ 407:
SWAP P%?I%, L%?(P%-I%)
NEXT
= A$</langsyntaxhighlight>
{{out}}
<pre>
Line 386 ⟶ 419:
 
=={{header|Bracmat}}==
<langsyntaxhighlight Bracmatlang="bracmat">( get'("unixdict.txt",STR):?dict
& new$hash:?H
& 0:?p
Line 409 ⟶ 442:
& out$(semordnilap !N dnuoF)
)
);</langsyntaxhighlight>
{{out}}
<pre>tv vt
Line 420 ⟶ 453:
=={{header|C}}==
 
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <alloca.h> /* stdlib.h might not have obliged. */
Line 485 ⟶ 518:
printf("Semordnilap pairs: %d\n", sem);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 496 ⟶ 529:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Net;
using System.Collections.Generic;
Line 534 ⟶ 567:
private static string Reversed(string value) => new string(value.Reverse().ToArray());
}</langsyntaxhighlight>
{{out}}
<pre>
Line 546 ⟶ 579:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <fstream>
#include <iostream>
#include <set>
#include <string>
 
int main() {
{
std::ifstream input("unixdict.txt");
if (!input) {
returnstd::set<std::string> 1words; // couldn'tprevious open input filewords
std::string word; // current word
}
size_t count = 0; // pair count
 
while (input >> word) {
std::set<std::string> words; // previous words
std::string drow(word.rbegin(), word.rend()); // current wordreverse
if (words.find(drow) == words.end()) {
size_t count = 0; // pair count
// pair not found
 
while (input >> words.insert(word) {;
} else {
std::string drow(word.rbegin(), word.rend()); // reverse
if (words.find(drow) == words.end()) { // pair not found
words.insert if (wordcount++ < 5);
std::cout << word << ' ' << drow << '\n';
} else { // pair found
if (count < 5) {
std::cout << word << ' ' << drow << '\n';
}
++count;
}
std::cout << "\nSemordnilap pairs: " << count << '\n';
}
return 0;
std::cout << "\nSemordnilap pairs: " << count << '\n';
} else
}</lang>
return 1; // couldn't open input file
}</syntaxhighlight>
{{out}}
<pre>
Line 587 ⟶ 619:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns rosettacode.semordnilaps
(:require [clojure.string :as str])
[clojure.java.io :as io ]))
Line 610 ⟶ 642:
dict-file)
 
(dorun (->> semordnilaps shuffle (take 5) sort (map println)))</langsyntaxhighlight>
 
{{out}}
Line 621 ⟶ 653:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun semordnilaps (word-list)
(let ((word-map (make-hash-table :test 'equal)))
(loop for word in word-list do
Line 641 ⟶ 673:
for word in words
do (print word)))
(values))</langsyntaxhighlight>
{{out}}
<pre>* (main)
Line 650 ⟶ 682:
("ah" . "ha")
("al" . "la")</pre>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">require "set"
 
UNIXDICT = File.read("unixdict.txt").lines
 
def word?(word : String)
UNIXDICT.includes?(word)
end
 
# is it a word and is it a word backwards?
semordnilap = UNIXDICT.select { |word| word?(word) && word?(word.reverse) }
 
# consolidate pairs like [bad, dab] == [dab, bad]
final_results = semordnilap.map { |word| [word, word.reverse].to_set }.uniq
 
# sets of N=1 mean the word is identical backwards
# print out the size, and 5 random pairs
puts final_results.size, final_results.sample(5)
</syntaxhighlight>
 
{{out}}
<pre>
246
[Set{"s's"}, Set{"eire", "erie"}, Set{"bag", "gab"}, Set{"mat", "tam"}, Set{"gel", "leg"}]
</pre>
 
=={{header|D}}==
===Simple Imperative Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.file, std.string, std.algorithm;
 
Line 671 ⟶ 729:
 
writeln("\nSemordnilap pairs: ", pairCount);
}</langsyntaxhighlight>
{{out}}
<pre>ca ac
Line 682 ⟶ 740:
 
===A More Functional Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.file, std.algorithm, std.string, std.range;
 
Line 690 ⟶ 748:
.zip(0.repeat).assocArray;
writeln(pairs.length, "\n", pairs.byKey.take(5));
}</langsyntaxhighlight>
{{out}}
<pre>158
[Tuple!(string, char[])("bag", "gab"), Tuple!(string, char[])("pat", "tap"), Tuple!(string, char[])("avis", "siva"), Tuple!(string, char[])("haw", "wah"), Tuple!(string, char[])("rot", "tor")]</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Classes}}
{{libheader| System.StrUtils}}
{{libheader| System.Diagnostics}}
<syntaxhighlight lang="delphi">
program Semordnilap;
 
{$APPTYPE CONSOLE}
{$R *.res}
 
uses
System.SysUtils,
System.Classes,
System.StrUtils,
System.Diagnostics;
 
function Sort(s: string): string;
var
c: Char;
i, j, aLength: Integer;
begin
aLength := s.Length;
 
if aLength = 0 then
exit('');
 
Result := s;
 
for i := 1 to aLength - 1 do
for j := i + 1 to aLength do
if result[i] > result[j] then
begin
c := result[i];
result[i] := result[j];
result[j] := c;
end;
end;
 
function IsAnagram(s1, s2: string): Boolean;
begin
if s1.Length <> s2.Length then
exit(False);
 
Result := Sort(s1) = Sort(s2);
 
end;
 
function CompareLength(List: TStringList; Index1, Index2: Integer): Integer;
begin
result := List[Index1].Length - List[Index2].Length;
if Result = 0 then
Result := CompareText(Sort(List[Index2]), Sort(List[Index1]));
end;
 
function IsSemordnilap(word1, word2: string): Boolean;
begin
Result := SameText(word1, ReverseString(word2));
end;
 
var
SemordnilapDict, Dict: TStringList;
Count, Index, i, j: Integer;
words: string;
StopWatch: TStopwatch;
 
begin
Randomize;
StopWatch := TStopwatch.Create;
StopWatch.Start;
 
Dict := TStringList.Create();
Dict.LoadFromFile('unixdict.txt');
 
SemordnilapDict := TStringList.Create;
 
Dict.CustomSort(CompareLength);
 
Index := Dict.Count - 1;
words := '';
Count := 1;
 
while Index - Count >= 0 do
begin
if IsAnagram(Dict[Index], Dict[Index - Count]) then
begin
if IsSemordnilap(Dict[Index], Dict[Index - Count]) then
begin
words := Dict[Index] + ' - ' + Dict[Index - Count];
SemordnilapDict.Add(words);
end;
Inc(Count);
end
else
begin
if Count > 2 then
for i := 1 to Count - 2 do
for j := i + 1 to Count - 1 do
begin
if IsSemordnilap(Dict[Index - i], Dict[Index - j]) then
begin
words := Dict[Index - i] + ' - ' + Dict[Index - j];
SemordnilapDict.Add(words);
end;
end;
 
Dec(Index, Count);
Count := 1;
end;
end;
 
StopWatch.Stop;
 
Writeln(Format('Time pass: %d ms [i7-4500U Windows 7]', [StopWatch.ElapsedMilliseconds]));
 
writeln(#10'Semordnilap found: ', SemordnilapDict.Count);
writeln(#10'Five random samples:'#10);
 
for Index := 0 to 4 do
writeln(' ', SemordnilapDict[Random(SemordnilapDict.Count)]);
 
SemordnilapDict.SaveToFile('Semordnilap.txt');
SemordnilapDict.Free;
Dict.Free;
Readln;
end.
 
</syntaxhighlight>
 
{{out}}
<pre>
Time pass: 558 ms [i7-4500U Windows 7]
 
Semordnilap found: 158
 
Five random samples:
 
on - no
me - em
peek - keep
ton - not
viva - aviv
</pre>
 
=={{header|EchoLisp}}==
We use the '''words''' library, and the french dictionary delivered with EchoLisp.
 
<langsyntaxhighlight lang="scheme">
(lib 'struct)
(lib 'sql)
Line 724 ⟶ 925:
(writeln 'pairs '→ (length semordnilap))
(writeln 'longest '→ (take semordnilap 5)))
</syntaxhighlight>
 
{{out}}
<pre>
(task)
pairs → 345
longest → (rengager tresser strasse reveler retrace)
</pre>
 
</lang>
 
=={{header|Eiffel}}==
First the programm reads the wordlist into an array.
Then it mirrors each word and searchs for it across the array using binary search.
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
SEMORDNILAP
Line 815 ⟶ 1,017:
 
end
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 852 ⟶ 1,054:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 864 ⟶ 1,066:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">words = File.stream!("unixdict.txt")
|> Enum.map(&String.strip/1)
|> Enum.group_by(&min(&1, String.reverse &1))
Line 870 ⟶ 1,072:
|> Enum.filter(&(length &1) == 2)
IO.puts "Semordnilap pair: #{length(words)}"
IO.inspect Enum.take(words,5)</langsyntaxhighlight>
 
{{out}}
Line 881 ⟶ 1,083:
=={{header|Erlang}}==
{{trans|Clojure}}
<langsyntaxhighlight lang="erlang">#!/usr/bin/env escript
main([]) -> main(["unixdict.txt"]);
 
Line 915 ⟶ 1,117:
[X||{_,X} <- lists:sort([ {random:uniform(), N} || N <- List])].
 
chop(L) -> [_|T] = lists:reverse(L), lists:reverse(T).</langsyntaxhighlight>
 
{{out}}
Line 927 ⟶ 1,129:
=={{header|F_Sharp|F#}}==
Using a mutable dictionary.
<langsyntaxhighlight lang="fsharp">open System
 
let seen = new System.Collections.Generic.Dictionary<string,bool>()
Line 943 ⟶ 1,145:
let s = Seq.toList sems
printfn "%d" s.Length
for i in 0 .. 4 do printfn "%A" s.[i]</langsyntaxhighlight>
{{out}}
<pre>158
Line 953 ⟶ 1,155:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs combinators.short-circuit formatting
io.encodings.utf8 io.files kernel literals locals make
prettyprint random sequences ;
Line 973 ⟶ 1,175:
]
] H{ } make >alist
[ length "%d semordnilap pairs.\n" printf ] [ 5 sample . ] bi</langsyntaxhighlight>
{{out}}
<pre>
Line 1,000 ⟶ 1,202:
The code uses two Gforth-specific words: EXECUTE-PARSING (implementable in standard Forth, but not easy) for allowing to provide the name of the defined word on the stack; and FIND-NAME-IN to look up the reversed word (could be replaced with a use of the standard SEARCH-WORDLIST, but the code would become a little more complicated).
 
<langsyntaxhighlight lang="forth">
wordlist constant dict
 
Line 1,036 ⟶ 1,238:
0 ' nt-semicheck dict traverse-wordlist cr .
cr bye
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,054 ⟶ 1,256:
 
 
<langsyntaxhighlight lang="fortran">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 21:50:08
Line 1,172 ⟶ 1,374:
 
end program Semordnilap
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight FreeBASIClang="freebasic">' version 20-06-2015
' compile with: fbc -s console
 
Line 1,254 ⟶ 1,456:
Print : Print "Hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Start reading unixdict.txt ... Done
Line 1,271 ⟶ 1,473:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,328 ⟶ 1,530:
fmt.Println(" ", e)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,341 ⟶ 1,543:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def semordnilapWords(source) {
def words = [] as Set
def semordnilaps = []
Line 1,349 ⟶ 1,551:
}
semordnilaps
}</langsyntaxhighlight>
Test Code
<langsyntaxhighlight lang="groovy">def semordnilaps = semordnilapWords(new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt'))
println "Found ${semordnilaps.size()} semordnilap words"
semordnilaps[0..<5].each { println "$it -> ${it.reverse()}" } </langsyntaxhighlight>
{{out}}
<pre>Found 158 semordnilap words
Line 1,363 ⟶ 1,565:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import qualified Data.Set as S
 
semordnilaps
Line 1,379 ⟶ 1,581:
let l = semordnilaps (lines s)
print $ length l
mapM_ (print . ((,) <*> reverse)) $ take 5 (filter ((4 <) . length) l)</langsyntaxhighlight>
{{out}}
<pre>158
Line 1,391 ⟶ 1,593:
 
The following solution works in both Icon and Unicon:
<langsyntaxhighlight lang="unicon">procedure main(a)
words := set()
found := 0
Line 1,402 ⟶ 1,604:
write("\nFound ",found," semordnilap words")
end
</syntaxhighlight>
</lang>
 
Sample run with unixdict:
Line 1,421 ⟶ 1,623:
We find all semordnilaps by filtering only words which, when reversed, are a member of the set of dictionary words and are not palindromes. We then find only unique semordnilaps by pairing them with their reversed instance, sorting each pair, and eliminating duplicates pairs:
 
<langsyntaxhighlight lang="j"> isSemordnilap=: |.&.> (~: *. e.) ]
unixdict=: <;._2 freads 'unixdict.txt'
#semordnilaps=: ~. /:~"1 (,. |.&.>) (#~ isSemordnilap) unixdict
158</langsyntaxhighlight>
 
We see that there are 158 semordnilaps.
Line 1,430 ⟶ 1,632:
Here's 5 of them, picked arbitrarily:
 
<syntaxhighlight lang="text"> (5?.158) { semordnilaps
┌────┬────┐
│kay │yak │
Line 1,441 ⟶ 1,643:
├────┼────┤
│caw │wac │
└────┴────┘</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|D}}
{{works with|Java|7+}}
<langsyntaxhighlight lang="java5">import java.nio.file.*;
import java.util.*;
 
Line 1,465 ⟶ 1,667:
System.out.println("\nSemordnilap pairs found: " + count);
}
}</langsyntaxhighlight>
<pre>ca ac
dab bad
Line 1,477 ⟶ 1,679:
===Node.js===
{{trans|Clojure}}
<langsyntaxhighlight lang="javascript">#!/usr/bin/env node
var fs = require('fs');
var sys = require('sys');
Line 1,516 ⟶ 1,718:
for (var i=0; i<5; ++i) {
sys.puts(semordnilaps[indices[i]]);
}</langsyntaxhighlight>
 
===Rhino===
{{works with|Rhino|1.7}}
 
<langsyntaxhighlight lang="javascript">#!/usr/bin/env rhino
 
importPackage (java.io)
Line 1,558 ⟶ 1,760:
for (var i=0; i<5; ++i) {
print(semordnilaps[indices[i]]);
}</langsyntaxhighlight>
 
{{out}}
Line 1,570 ⟶ 1,772:
===macOS JavaScript for Automation===
{{Trans|Python}}
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,629 ⟶ 1,831:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>158
Line 1,651 ⟶ 1,853:
* time /usr/local/bin/jq -M -s -R -r -f semordnilap.jq unixdict.txt
user 0m0.440s; sys 0m0.010s
<syntaxhighlight lang="jq">
<lang jq>
# Produce a stream
def report:
Line 1,662 ⟶ 1,864:
| (. < $rev and $dict[$rev]) );
 
[report] | (.[0:5][], "length = \(length)")</langsyntaxhighlight>
{{Out}}
able
Line 1,672 ⟶ 1,874:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">raw = readdlm("unixdict.txt",String)[:]
inter = intersect(raw,map(reverse,raw)) #find the matching strings/revstrings
res = String[b == 1 && a != reverse(a) && a < reverse(a) ? a : reverse(a) for a in inter, b in 1:2] #create pairs
res = res[res[:,1] .!= res[:,2],:] #get rid of duplicates, palindromes</langsyntaxhighlight>
<pre>julia> length(res[:,1])
158
Line 1,689 ⟶ 1,891:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.io.File
Line 1,699 ⟶ 1,901:
println("Found ${pairs.size} semordnilap pairs")
println(pairs.take(5))
}</langsyntaxhighlight>
 
{{out}}
Line 1,706 ⟶ 1,908:
[(able, elba), (abut, tuba), (ac, ca), (ah, ha), (al, la)]
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Semordnilap
 
# # Variables:
#
integer MIN_WORD_LEN=1 TRUE=1 FALSE=0
dict='/home/ostrande/prj/roscode/unixdict.txt'
 
integer i j=0 k=0
typeset -A word
 
# # Functions:
#
 
# # Function _flipit(string) - return flipped string
#
function _flipit {
typeset _buf ; _buf="$1"
typeset _tmp ; unset _tmp
 
for (( _i=$(( ${#_buf}-1 )); _i>=0; _i-- )); do
_tmp="${_tmp}${_buf:${_i}:1}"
done
 
echo "${_tmp}"
}
 
# # Function _isword(word, wordlist) - return 1 if word in wordlist
#
function _isword {
typeset _word ; _word="$1"
typeset _wordlist ; nameref _wordlist="$2"
 
[[ ${_word} == @(${_wordlist}) ]] && return $TRUE
return $FALSE
}
 
######
# main #
######
# # Due to the large number of words in unixdist.txt subgroup by 1st letter and length
# # only accept words containing alpha chars and > 1 chars
#
while read; do
[[ $REPLY != *+(\W)* ]] && [[ $REPLY != *+(\d)* ]] && \
(( ${#REPLY} > MIN_WORD_LEN )) && word[${REPLY:0:1}][${#REPLY}]+=( $REPLY )
done < ${dict}
 
print Examples:
for fl in ${!word[*]}; do # Over $fl first letter
for len in ${!word[${fl}][*]}; do # Over $len word length
for ((i=0; i<${#word[${fl}][${len}][*]}; i++)); do
Word=${word[${fl}][${len}][i]} # dummy
Try=$(_flipit ${Word})
if [[ ${Try} != ${Word} ]]; then # no palindromes
unset words
oldIFS="$IFS" ; IFS='|' ; words=${word[${Try:0:1}][${#Try}][*]} ; IFS="${oldIFS}"
_isword "${Try}" words
if (( $? )); then
if [[ ${Try} != @(${uniq%\|*}) ]]; then
((++j))
(( ${#Word} >= 5 )) && (( k<=5 )) && print $((++k)). ${Word} ${Try}
uniq+="${Try}|${Word}|"
fi
fi
fi
done
done
done
echo ; print ${j} pairs found.</syntaxhighlight>
{{out}}<pre>
Examples:
1. damon nomad
2. kramer remark
3. lager regal
4. leper repel
5. lever revel
 
158 pairs found.</pre>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(
words = string(include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt')) -> split('\n'),
semordnilaps = array,
Line 1,736 ⟶ 2,021:
#found_size
'<br />'
#examples</langsyntaxhighlight>
{{out}}
<pre>Total found: 158
Line 1,742 ⟶ 2,027:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print "Loading dictionary."
open "unixdict.txt" for input as #1
Line 1,787 ⟶ 2,072:
Next i
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,800 ⟶ 2,085:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">#!/usr/bin/env lua
-- allow dictionary file and sample size to be specified on command line
local dictfile = arg[1] or "unixdict.txt"
Line 1,833 ⟶ 2,118:
semordnilaps[j] = nil
print(f .. " -> " .. r)
end</langsyntaxhighlight>
 
{{out}}
Line 1,844 ⟶ 2,129:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module semordnilaps {
Document d$
Line 1,871 ⟶ 2,156:
}
semordnilaps
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,882 ⟶ 2,167:
</pre >
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">data = Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"];
result = DeleteDuplicates[ Select[data, MemberQ[data, StringReverse[#]]
&& # =!= StringReverse[#] &], (# ===StringReverse[#2]) &];
Print[Length[result], Take[result, 5]]</langsyntaxhighlight>
{{out}}
<pre>158 {able,abut,ac,ah,al}</pre>
Line 1,892 ⟶ 2,177:
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight lang="nanoquery">import Nanoquery.IO
 
def reverse_str(string)
Line 1,920 ⟶ 2,205:
end
 
println "\nSemordnilap pairs found: " + count</langsyntaxhighlight>
{{out}}
<pre>ca ac
Line 1,932 ⟶ 2,217:
=={{header|NetRexx}}==
{{Trans|REXX}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,961 ⟶ 2,246:
Say pi 'words in' fid 'have a palindrome' /* total number found */
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,970 ⟶ 2,255:
bard drab
158 words in unixdict.txt have a palindrome
</pre>
 
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
;;; Get the words as a list, splitting at newline
(setq data
(parse (get-url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
"\n"))
;
;;; destructive reverse wrapped into a function
(define (get-reverse x) (reverse x))
;
;;; stack of the results
(setq res '())
;
;;; Find the semordlinap and put them on the stack
(dolist (x data)
(let (y (get-reverse x))
(if (and
(member y data) ; reverse is a dictionary word
(!= x y) ; but not a palindrome
(not (member y res))) ; not already stacked
(push x res -1))))
;
;;; Count results
(println "Found " (length res) " pairs.")
(println)
;;; Show the longest ones
(dolist (x res)
(if (> (length x) 4) (println x " -- " (get-reverse x))))
</syntaxhighlight>
{{out}}
<pre>
Found 158 pairs.
 
damon -- nomad
kramer -- remark
lager -- regal
leper -- repel
lever -- revel
</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils, sequtils, sets, algorithm
 
proc reversereversed(s: string): string =
result = newString(s.len)
for i, c in s:
result[s.high - i] = c
 
let
words = readFile("unixdict.txt").strip().splitLines()
wordset = words.toSettoHashSet
revs = words.map(reversereversed)
var pairs = zip(words, revs).filterIt(it[0] < it[1] and it[1] in wordset)
 
echo "Total number of semordnilaps: ", pairs.len
pairs.sort(proc (x,y): auto = cmppairs.sortedByIt(x[0].len,yit[0].len))
echo pairs[pairs^5.high-4..pairs.high^1]</langsyntaxhighlight>
 
{{out}}
<pre>Total number of semordnilaps: 158
Line 1,994 ⟶ 2,320:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">module StrSet = Set.Make(String)
 
let str_rev s =
Line 2,027 ⟶ 2,353:
let (word, rev) = List.nth pairs (Random.int len) in
Printf.printf " %s %s\n" word rev
done</langsyntaxhighlight>
 
{{out}}
Line 2,040 ⟶ 2,366:
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">a = strsplit(fileread("unixdict.txt"), "\n");
a = intersect(a, cellfun(@fliplr, a, "UniformOutput", false));
a = a(arrayfun(@(i) ismember(fliplr(a{i}), a(i+1:length(a))), 1:length(a)));
length(a)
arrayfun(@(i) printf("%s %s\n", a{i}, fliplr(a{i})), 1:5)</langsyntaxhighlight>
 
'''Output:'''
Line 2,058 ⟶ 2,384:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: semordnilap
| w wr wrds |
ListBuffer new ->wrds
Line 2,065 ⟶ 2,391:
wrds include(w reverse dup ->wr) ifTrue: [ [wr, w] over add ]
w wr < ifTrue: [ wrds add(w) ]
] ;</langsyntaxhighlight>
 
{{out}}
Line 2,075 ⟶ 2,401:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">while (<>) {
chomp;
my $r = reverse;
Line 2,081 ⟶ 2,407:
}
 
print "$c\n"</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence words={}, semilordnaps={}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
object word
<span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">unix_dict</span><span style="color: #0000FF;">(),</span> <span style="color: #000000;">semordnilap</span><span style="color: #0000FF;">={}</span>
constant fn = open("demo\\unixdict.txt","r")
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">word</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
while 1 do
<span style="color: #008080;">if</span> <span style="color: #7060A8;">rfind</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">),</span><span style="color: #000000;">words</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
word = trim(gets(fn))
<span style="color: #000000;">semordnilap</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">semordnilap</span><span style="color: #0000FF;">,</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span>
if atom(word) then exit end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if find(reverse(word),words) then
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
semilordnaps = append(semilordnaps,word)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d semordnilap found, the first five are:\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">semordnilap</span><span style="color: #0000FF;">))</span>
end if
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">5</span> <span style="color: #008080;">do</span>
words = append(words,word)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s - %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">semordnilap</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">semordnilap</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])})</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
close(fn)
?length(semilordnaps)
for i=1 to 5 do
word = semilordnaps[i]
printf(1,"%s - %s\n",{word,reverse(word)})
end for</lang>
{{out}}
<pre>
158 semordnilap found, the first five are:
158
ca - ac
ca - ac
dab - bad
dab - bad
diva - avid
diva - avid
dna - and
dna - and
drab - bard
drab - bard
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">include ..\Utilitys.pmt
 
( ) ( )
 
"unixdict.txt" "r" fopen var f
 
true while
f fgets
dup -1 == if
drop
f fclose
false
else
-1 del
0 put
true
endif
endwhile
 
len while
len 1 > if
pop swap reverse find dup
if
extract rot swap 0 put swap
else
drop
endif
true
else
drop false
endif
endwhile
 
( 50 54 ) for get dup reverse print " -> " print ? endfor nl
len print " pairs" ?</syntaxhighlight>
{{out}}
<pre>dew -> wed
dial -> laid
dim -> mid
dine -> enid
dog -> god
 
158 pairs
 
=== Press any key to exit ===</pre>
 
=={{header|PHP}}==
{{trans|Raku}}
<langsyntaxhighlight lang="php"><?php
// Read dictionary into array
$dictionary = array_fill_keys(file(
Line 2,130 ⟶ 2,497:
// array_rand() returns keys, not values
foreach (array_rand($words, 5) as $word)
echo "$word $words[$word]\n";</langsyntaxhighlight>
{{out}}
<pre>158
Line 2,140 ⟶ 2,507:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Semordnilap
(mapcon
'((Lst)
Line 2,146 ⟶ 2,513:
(cons (pack (car Lst))) ) )
(make (in "unixdict.txt" (while (line) (link @)))) )
(println (length Semordnilap) (head 5 Semordnilap)) )</langsyntaxhighlight>
{{out}}
<pre>158 ("able" "abut" "ac" "ah" "al")</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
find: procedure options (main); /* 20/1/2013 */
declare word character (20) varying controlled;
Line 2,193 ⟶ 2,560:
end;
end find;
</syntaxhighlight>
</lang>
<pre>
There are 158 pairs.
Line 2,207 ⟶ 2,574:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Reverse-String ([string]$String)
{
Line 2,243 ⟶ 2,610:
 
"`nSemordnilap count: {0}" -f ($semordnilap.GetEnumerator() | Measure-Object).Count
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,261 ⟶ 2,628:
Semordnilap count: 158
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">If OpenConsole("")=0 : End 1 : EndIf
If ReadFile(0,"./Data/unixdict.txt")=0 : End 2 : EndIf
NewList dict$()
 
While Eof(0)=0 : AddElement(dict$()) : dict$()=Trim(ReadString(0)) : Wend : CloseFile(0)
 
While FirstElement(dict$())
buf$=dict$() : DeleteElement(dict$())
If buf$="" : Continue : EndIf
xbuf$=ReverseString(buf$)
ForEach dict$()
If xbuf$=dict$()
res$+buf$+" / "+xbuf$+#LF$
Break
EndIf
Next
Wend
 
PrintN("Semordnilap pairs found: "+Str(CountString(res$,#LF$)))
For k=1 To 5
If k=1 : PrintN(~"\nFirst 5 pairs: "+StringField(res$,k,#LF$)) : Continue : EndIf
PrintN(Space(15)+StringField(res$,k,#LF$))
Next
Input()</syntaxhighlight>
{{out}}
<pre>Semordnilap pairs found: 158
 
First 5 pairs: able / elba
abut / tuba
ac / ca
ah / ha
al / la</pre>
 
=={{header|Python}}==
===Idiomatic===
<langsyntaxhighlight lang="python">>>> with open('unixdict.txt') as f:
wordset = set(f.read().strip().split())
 
>>> revlist = (''.join(word[::-1]) for word in wordset)
>>> pairs = set((wrdword, rev) for wrdword, rev in zip(wordset, revlist)
if wrdword < rev and rev in wordset)
>>> len(pairs)
158
>>> sorted(pairs, key=lambda p: (len(p[0]), p))[-5:]
[('damon', 'nomad'), ('lager', 'regal'), ('leper', 'repel'), ('lever', 'revel'), ('kramer', 'remark')]
>>> </langsyntaxhighlight>
 
{{trans|Perl 6}}
<lang python>import os
import random
# Load file and put it to dictionary as set
dictionary = {word.rstrip(os.linesep) for word in open('unixdict.txt')}
 
# List of results
results = []
for word in dictionary:
# [::-1] reverses string
reversed_word = word[::-1]
if reversed_word in dictionary and word > reversed_word:
results.append((word, reversed_word))
 
print(len(results))
for words in random.sample(results, 5):
print(' '.join(words))</lang>
{{out}}
<pre>158
nob bon
mac cam
dub bud
viva aviv
nomad damon</pre>
 
===As a fold, using reduce===
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Dictionary words paired by equivalence under reversal'''
 
from functools import (reduce)
Line 2,414 ⟶ 2,790:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Dictionary words paired by equivalence under reversal:
Line 2,430 ⟶ 2,806:
Requires the <code>requests</code> library.
 
<langsyntaxhighlight lang="python">import sys
import random
import requests
Line 2,470 ⟶ 2,846:
print(
f'found {len(semordnilaps)} semordnilap usernameswords:',
* ['%s %s' % p for p in example_pairs]+['...'],
sep='\n'
Line 2,480 ⟶ 2,856:
if __name__ == '__main__':
main(*sys.argv[1:])
</syntaxhighlight>
</lang>
 
{{Out}}
<pre>
found 158 semordnilap usernameswords:
mug gum
revel lever
Line 2,492 ⟶ 2,868:
...
</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> []
$ "rosetta/unixdict.txt" sharefile drop
nest$
[ behead reverse swap
2dup find over found iff
[ dip [ nested join ] ]
else nip
dup [] = until ]
drop
say "Number of semordnilaps: "
dup size echo cr
sortwith [ size swap size > ]
5 split drop
say "Five longest: "
witheach
[ dup echo$ say "<->"
reverse echo$ sp ]</syntaxhighlight>
 
{{out}}
 
<pre>Number of semordnilaps: 158
Five longest: remark<->kramer nomad<->damon regal<->lager repel<->leper revel<->lever
</pre>
 
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define seen (make-hash))
Line 2,509 ⟶ 2,912:
(for ([s (take (sort semordnilaps > #:key (compose1 string-length car)) 5)])
(apply printf " ~s ~s\n" s))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,525 ⟶ 2,928:
(formerly Perl 6)
{{works with|rakudo|2015-10-26}}
<syntaxhighlight lang="raku" perl6line>my $words = set slurp("unixdict.txt").lines;
 
my @sems = gather for $words.flat -> $word {
Line 2,532 ⟶ 2,935:
}
 
say $_ ~ ' ' ~ $_.flip for @sems.pick(5);</langsyntaxhighlight>
{{out}}
<pre>abut tuba
Line 2,542 ⟶ 2,945:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 07.09.2012 Walter Pachl
**********************************************************************/
Line 2,560 ⟶ 2,963:
End
End
Say pi 'words in' fid 'have a palindrome' /* total number found */</langsyntaxhighlight>
{{out}}
<pre>
Line 2,573 ⟶ 2,976:
===version 2===
This REXX version makes use of sparse (stemmed) arrays.
 
<br><br>The dictionary file wasn't assumed to be in any particular case (upper/lower/mixed).
The dictionary file wasn't assumed to be in any particular case (upper/lower/mixed).
<br>For instance, &nbsp; '''DNA''' &nbsp; <big> &amp; </big> &nbsp; '''and''' &nbsp; would be considered palindromes.
 
<br>The UNIXDICT dictionary specified to be used ''is'' all lowercase, however, but the REXX
For instance, &nbsp; '''DNA''' &nbsp; <big> &amp; </big> &nbsp; '''and''' &nbsp; would be considered semordnilaps, &nbsp; even though their &nbsp; ''case'' &nbsp; is different.
<br>program assumes that the words may be in any ''case''.
 
<br><br>The order of the words in the dictionary isn't important.
The UNIXDICT dictionary specified to be used ''is'' all lowercase, however, but the REXX program assumes that the
<br>Any blank lines or ''duplicate words'' in the dictionary are ignored (as duplicate words wouldn't make them unique).
<br>words may be in any &nbsp; ''case'' &nbsp; (lowercase/uppercase/mixedcased).
<br>Any leading, trailing, or imbedded blanks are also ignored (as well as tab characters or other whitespace).
 
<br>The palindrome pairs are shown with a comma delimiter in case there're phrases (words with imbedded blanks like Sing Sing).
<br>The (firstorder five)of palindromethe pairs are shown as they are specified (respective to case)words in the dictionary isn't important.
 
<lang rexx>/*REXX program finds palindrome pairs in a dictionary (the default is UNIXDICT.TXT). */
Any blank lines or ''duplicate words'' in the dictionary are ignored (as duplicate words wouldn't make them unique).
#=0 /*number palindromes (so far).*/
 
parse arg iFID .; if iFID=='' then iFID='UNIXDICT.TXT' /*Not specified? Use default.*/
Any leading, trailing, or imbedded blanks are also ignored (as well as tab characters or other whitespace).
@.= /*uppercase no─duplicated word*/
 
do while lines(iFID)\==0; _=space(linein(iFID),0) /*read a word from dictionary.*/
The semordnilap word pairs are shown with a comma delimiter in case there are phrases &nbsp; (words with imbedded
parse upper var _ u /*obtain an uppercase version.*/
<br>blanks like &nbsp; ''Sing Sing'').
if length(_)<2 | @.u\=='' then iterate /*can't be a unique palindrome*/
 
r=reverse(u) /*get the reverse of the word.*/
The (first five) semordnilap pairs are shown as they are specified/defined (respective to case) in the dictionary.
if @.r\=='' then do; #=#+1 /*find a palindrome pair ? */
<syntaxhighlight lang="rexx">/*REXX program finds N semordnilap pairs using a specified dictionary (UNIXDICT.TXT).*/
if #<6 then say @.r',' _ /*just show 1st 5 palindromes.*/
parse arg n iFID end . /*obtain [↑]optional argument bumpfrom palindromethe countCL.*/
if @.un==_'' | n=="," then n= 5 /*Not specified? Then use the /*define a unique palindromedefault. */
if iFID=='' | iFID=="," end then iFID='UNIXDICT.TXT' /*while*/ " " " " " " /* [↑] read the dictionary. */
#= 0 /*number of semordnilaps (so far). */
@.= /*caseless non─duplicated dict. words. */
do while lines(iFID)\==0; _= linein(iFID); u= space(_, 0); upper u /*get a word.*/
if length(u)<2 | @.u\=='' then iterate /*word can't be a unique semordnilap. */
r= reverse(u) /*obtain reverse of the dictionary word*/
if @.r\=='' then do; #= # + 1 /*found a semordnilap word; bump count.*/
if #<=n then say right(@.r, max(32, length(@.r) ) )',' u
end
@.u= _ /*define reverse of the dictionary word*/
end /*while*/ /*stick a fork in it, we're all done. */
say
say "There're " # ' unique palindromesemordnilap pairs in the dictionary file: ' iFID</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
/*stick a fork in it, we're done. */</lang>
'''output''' &nbsp; when using the default dictionary as the input:
<pre>
ac, ca
ac, ca
bad, dab
avid, diva
and, dna
bard, drab
 
There're 158 unique palindromesemordnilap pairs in the dictionary file: UNIXDICT.TXT
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Semordnilap
 
Line 2,635 ⟶ 3,047:
nr = find(aList,bString)
return nr
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,648 ⟶ 3,060:
=={{header|Ruby}}==
Note: An alternative (old fashioned) method of solving this task (not using a Set as done by other solutions) is to produce 2 sorted files and walk through them. This can be done entirly on disk if required, when done in memory it is faster than a set for large samples.--[[User:Nigel Galloway|Nigel Galloway]] 11:12, 17 September 2012 (UTC)
<langsyntaxhighlight Rubylang="ruby">dict = File.readlines("unixdict.txt").collect(&:strip)
i = 0
res = dict.collect(&:reverse).sort.select do |z|
Line 2,655 ⟶ 3,067:
end
puts "There are #{res.length} semordnilaps, of which the following are 5:"
res.take(5).each {|z| puts "#{z} #{z.reverse}"}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,667 ⟶ 3,079:
 
Another way
<langsyntaxhighlight Rubylang="ruby">words = File.readlines("unixdict.txt")
.group_by{|x| [x.strip!, x.reverse].min}
.values
.select{|v| v.size==2}
puts "There are #{words.size} semordnilaps, of which the following are 5:"
words.take(5).each {|a,b| puts "#{a} #{b}"}</langsyntaxhighlight>
output is the same above.
 
=={{header|Rust}}==
{{trans|Java}}
<syntaxhighlight lang="rust">use std::collections::HashSet;
use std::fs::File;
use std::io::{self, BufRead};
use std::iter::FromIterator;
 
fn semordnilap(filename: &str) -> std::io::Result<()> {
let file = File::open(filename)?;
let mut seen = HashSet::new();
let mut count = 0;
for line in io::BufReader::new(file).lines() {
let mut word = line?;
word.make_ascii_lowercase();
let rev = String::from_iter(word.chars().rev());
if seen.contains(&rev) {
if count < 5 {
println!("{}\t{}", word, rev);
}
count += 1;
} else {
seen.insert(word);
}
}
println!("\nSemordnilap pairs found: {}", count);
Ok(())
}
 
fn main() {
match semordnilap("unixdict.txt") {
Ok(()) => {}
Err(error) => eprintln!("{}", error),
}
}</syntaxhighlight>
 
{{out}}
<pre>
ca ac
dab bad
diva avid
dna and
drab bard
 
Semordnilap pairs found: 158
</pre>
===A Shortened Version===
<syntaxhighlight lang="rust">use std::{collections::HashSet, fs};
 
fn reverse(x: &str) -> String {
x.chars().rev().collect::<String>()
}
 
fn main() {
let content = fs::read_to_string("unixdict.txt").expect("No file found!");
let work: HashSet<&str> = content.lines().collect();
 
let mut candidats: Vec<&str> = work.clone().into_iter().collect();
candidats.retain(|&x| work.contains(&reverse(x).as_str()) && x < reverse(x).as_str());
 
println!("Numbers of pairs found: {}", candidats.len());
for ind in 0..5 {
println!("{}, {}", candidats[ind], reverse(candidats[ind]));
}
}</syntaxhighlight>
{{out}}
<pre>Numbers of pairs found: 158
mn, nm
map, pam
saw, was
deep, peed
door, rood</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">val wordsAll =
<lang scala>val wordsAll = scala.io.Source.fromURL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").getLines.map(_.toLowerCase).to[IndexedSeq]
scala.io.Source.
fromURL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").
getLines().map(_.toLowerCase).toIndexedSeq
 
 
/**
Line 2,683 ⟶ 3,171:
* words are different.
*/
def semordnilap( words:SeqIndexedSeq[String] ) : SeqIndexedSeq[(String,String)] = {
 
( words.
zipWithIndex. // index will be needed to eliminate duplicate
filter {
case (w,i) =>
val j = words.indexOf(w.reverse) // eg. (able,62) and (elba,7519)
i < j && w != w.reverse // save the matches which are not palindromes
}.
map {
case (w,_) => (w,w.reverse) // drop the index
}
).
map {
case (w,i) => (w,w.reverse) // drop the index
}
}
 
Line 2,701 ⟶ 3,188:
 
{
println( s"${ss.size + "} matches, including: \n" )
println( ss.take(5).mkString( "\n" ) )
}</langsyntaxhighlight>
{{out}}
<pre>158 matches, including:
Line 2,715 ⟶ 3,202:
 
=={{header|Seed7}}==
Note that the Seed7 program downloads unixdict.txt from the net.
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "gethttp.s7i";
 
const func string: reverse (in string: word) is func
result
var string: drow is "";
local
var integer: index is 0;
begin
for index range length(word) downto 1 do
drow &:= word[index];
end for;
end func;
 
const proc: main is func
Line 2,737 ⟶ 3,214:
var integer: count is 0;
begin
wordList := split(lower(getHttp("wwwwiki.puzzlers.org/pub/wordlists/unixdict.txt")), "\n");
for word range wordList do
drow := reverse(word);
Line 2,751 ⟶ 3,228:
writeln;
writeln("Semordnilap pairs: " <& count);
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,766 ⟶ 3,243:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var c = 0
var seen = Hash()
 
Line 2,776 ⟶ 3,253:
}
 
say c</langsyntaxhighlight>
{{out}}
<pre>
Line 2,786 ⟶ 3,263:
drab bard
158
</pre>
 
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
<syntaxhighlight lang="snobol4">
* Program: semordnilap.sbl
* To run: sbl semordnilap.sbl < unixdict.txt
* Description: 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
* Reads file unixdict.txt
* Comment: Tested using the Spitbol for Linux version of SNOBOL4
 
output = "Some Semordnilap Pairs from File unixdict.txt"
atable = table(25200,,-1)
ntable = table(25200,,-2)
 
* Read dictionary file into memory
in1
word = input :f(p1)
count = count + 1
atable[word] = word
ntable[count] = word
:(in1)
 
* Process dictionary to find unique semordnilaps
p1
i = lt(i,count) i + 1 :f(p2)
newword = atable[reverse(ntable[i])]
leq(newword,-1) :s(p1)
ident(ntable[i],newword) :s(p1)
output = lt(outcount,5) ntable[i] ', ' newword
atable[ntable[i]] = atable[newword] = -1
outcount = outcount + 1
:(p1)
p2
output = 'The number of semordnilap pairs is: ' outcount
END
</syntaxhighlight>
{{out}}
<pre>
Some Semordnilap Pairs from File unixdict.txt
able, elba
abut, tuba
ac, ca
ah, ha
al, la
The number of semordnilap pairs is: 158
</pre>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">set seed 17760704
import delimited http://www.puzzlers.org/pub/wordlists/unixdict.txt, clear
save temp, replace
Line 2,807 ⟶ 3,333:
| nit tin |
| ku uk |
+-------------+</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
{{incorrect|SuperCollider|The number of pairs should be 158.}}
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
var text, words, sdrow, semordnilap, selection;
File.use("unixdict.txt".resolveRelative, "r", { |f| x = text = f.readAllString });
Line 2,822 ⟶ 3,348:
selection = semordnilap.select { |each| each.size >= 4 }.scramble.keep(4);
selection.do { |each| "% %\n".postf(each, each.reverse); };
)</langsyntaxhighlight>
 
Answers:
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
There are 405 in unixdict.txt
For example those, with more than 3 characters:
Line 2,832 ⟶ 3,358:
drib bird
eros sore
</syntaxhighlight>
</lang>
 
This seems wrong, but perhaps the test file has changed?
Line 2,838 ⟶ 3,364:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">guard let data = try? String(contentsOfFile: "unixdict.txt") else {
fatalError()
}
Line 2,848 ⟶ 3,374:
 
print("Found \(pairs.count) pairs")
print("Five examples: \(pairs.prefix(5))")</langsyntaxhighlight>
 
{{out}}
Line 2,856 ⟶ 3,382:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require http
 
Line 2,885 ⟶ 3,411:
puts "Example: $pair"
if {[incr i]>=5} break
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,894 ⟶ 3,420:
Example: eros/sore
Example: bard/drab
</pre>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
MainModule: {
_start: (λ (with fs FileStream()
(open-r fs "/mnt/vault/tmp/unixdict.txt") )
(with v ( -|
(read-text fs)
(split)
(group-by (λ s String() -> String()
(ret (min s (reverse (cp s))))))
(values)
(filter where: (λ v Vector<String>() (ret (== (size v) 2))))
(shuffle))
 
(lout "Total number of semordnilaps: " (size v))
(lout "Random five: " Range(in: v 0 5))))
)
}</syntaxhighlight>
{{out}}
<pre>
Total number of semordnilaps: 158
Random five: [[deer, reed], [nip, pin], [eire, erie], [am, ma], [gem, meg]]
</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
Line 2,921 ⟶ 3,472:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,931 ⟶ 3,482:
4. ah'ha
5. al'la
</pre>
 
=={{header|Uiua}}==
For each word check its reverse is in the array, and that it's greater. This removes palindromes and also keeps only first of each pair.
 
<syntaxhighlight lang="Uiua">
&p &pf "Count: " ⧻.▽≡(×>⇌.⟜∊⇌)⟜¤. ⊜□ ≠@\n. &fras "unixdict.txt"
</syntaxhighlight>
{{out}}
<pre>
Count: 158
{"able" "abut" "ac" "ah" "al" "am" "amos" "and" "ape" "aps" "are"
...
"pot" "pow" "pus" "rat" "raw" "rot" "saw" "suez" "tort" "tv" "way"}
</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
Line 2,971 ⟶ 3,536:
Set objUnixDict = Nothing
Set objSemordnilap = Nothing
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,981 ⟶ 3,546:
drab - bard
Total Count: 158
</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">import "io" for File
 
var dict = File.read("unixdict.txt").split("\n")
var wmap = {}
dict.each { |w| wmap[w] = true }
var pairs = []
var used = {}
for (word in dict) {
if (word != "") {
var pal = word[-1..0]
if (word != pal && wmap[pal] && !used[pal]) {
pairs.add([word, pal])
used[word] = true
}
}
}
System.print("There are %(pairs.count) unique semordnilap pairs in the dictionary.")
System.print("\nIn sorted order, the first five are:")
for (i in 0..4) System.print(" %(pairs[i][0]), %(pairs[i][1])")
System.print("\nand the last five are:")
for (i in -5..-1) System.print(" %(pairs[i][0]), %(pairs[i][1])")</syntaxhighlight>
 
{{out}}
<pre>
There are 158 unique semordnilap pairs in the dictionary.
 
In sorted order, the first five are:
able, elba
abut, tuba
ac, ca
ah, ha
al, la
 
and the last five are:
saw, was
suez, zeus
tort, trot
tv, vt
way, yaw
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
def LF=$0A, CR=$0D, EOF=$1A;
Line 3,043 ⟶ 3,650:
];
IntOut(0, Count); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,054 ⟶ 3,661:
158
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">dim norm$(27000), result$(270, 2)
 
print "Start reading unixdict.txt"
open "i:\unixdict.txt" for reading as #1
 
while not(eof(#1)) // read to end of file
line input #1 in_str$ // get line = word
in_str$ = trim$(in_str$) // we don//t want spaces
if len(in_str$) > 1 then // if length > 1 then reverse$
rev$ = reverse$(in_str$)
if in_str$ <> rev$ then // if in_str is not a palingdrome
count = count + 1 // increase counter
norm$(count) = in_str$ // store in the array
big$ = big$ + rev$ + " " // create big string with reverse$d words
fi
fi
wend
 
close #1
print " ... Done"
print
print "Start looking for semordnilap"
 
for i = 1 to count
for j = 1 to amount // check to avoid the double
if result$(j, 2) = norm$(i) continue
next j
j = instr(big$, " " + norm$(i) + " ")
if j <> 0 then // found one
amount = amount + 1 // increase counter
result$(amount, 1) = norm$(i) // store normal word
result$(amount, 2) = reverse$(norm$(i)) // store reverse$ word
fi
next i
 
print
print "Found", amount, " unique semordnilap pairs"
print
print "Display 5 semordnilap pairs"
print
 
count = 0
for i = 1 to amount
if len(result$(i, 1)) >= 5 then
count = count + 1
print result$(i, 1), chr$(9), result$(i, 2)
if count >= 5 break
fi
next i
end
 
sub reverse$(norm$)
local rev$, i, l
l = len(norm$) - 1
rev$ = norm$
for i = 0 to l
mid$(rev$, l - i, 1) = mid$(norm$, i, 1)
next i
return rev$
end sub</syntaxhighlight>
{{out}}
<pre>
Start reading unixdict.txt
... Done
 
Start looking for semordnilap
 
Found70 unique semordnilap pairs
 
Display 5 semordnilap pairs
 
diesel seidel
dirge ridge
gamma magma
groan organ
latus talus
 
---Program done, press RETURN---</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var [const] words= // create hashed unixdict of striped words (word:True, ...)
File("dict.txt").howza(11).pump(Dictionary().howza(8).add.fp1(True));
ss:=words.pump(List, // push stripped unixdict words through some functions
Line 3,064 ⟶ 3,752:
 
ss.len().println(); //--> 158
ss.shuffle()[0,5].println();</langsyntaxhighlight>
{{out}}
<pre>
Line 3,072 ⟶ 3,760:
 
 
{{omit from|6502 Assembly|unixdict.txt is much larger than the CPU's address space.}}
{{omit from|8080 Assembly|See 6502 Assembly.}}
{{omit from|Brlcad}}
{{omit from|GUISS}}
Line 3,077 ⟶ 3,767:
{{omit from|Openscad}}
{{omit from|TPP}}
{{omit from|Z80 Assembly|See 6502 Assembly.}}
{{omit from|ZX Spectrum Basic}}
62

edits