Semordnilap: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
Line 18:
{{trans|Python}}
 
<langsyntaxhighlight 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..])</langsyntaxhighlight>
 
{{out}}
Line 33:
=={{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 51:
a:shuffle
( a:shift dup . " is the reverse of " . s:rev . cr ) 5 times bye
</syntaxhighlight>
</lang>
 
{{out}}
Line 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 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 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 156:
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("pairs found:" & Integer'Image(Semi_Counter));
end Semordnilap;</langsyntaxhighlight>
 
{{out}}
Line 169:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer p, z;
record r;
file f;
Line 189:
}
 
o_form("Semordnilap pairs: ~\n", p);</langsyntaxhighlight>
{{out}}
<pre>ca ac
Line 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 262:
close( input file );
print( ( whole( semordnilap count, 0 ), " semordnilaps found", newline ) )
FI</langsyntaxhighlight>
{{out}}
<pre>
Line 274:
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">words: read.lines "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
pairs: []
loop words 'wrd [
Line 286:
unique 'pairs
 
print map 1..5 => [sample pairs]</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">S := [], M := []
 
FileRead, dict, unixdict.txt
Line 311:
r := A_LoopField . r
return r
}</langsyntaxhighlight>
{{out}}
<pre>5 Examples:
Line 324:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SEMORDNILAP.AWK unixdict.txt
{ arr[$0]++ }
Line 345:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 358:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Line 407:
SWAP P%?I%, L%?(P%-I%)
NEXT
= A$</langsyntaxhighlight>
{{out}}
<pre>
Line 419:
 
=={{header|Bracmat}}==
<langsyntaxhighlight Bracmatlang="bracmat">( get'("unixdict.txt",STR):?dict
& new$hash:?H
& 0:?p
Line 442:
& out$(semordnilap !N dnuoF)
)
);</langsyntaxhighlight>
{{out}}
<pre>tv vt
Line 453:
=={{header|C}}==
 
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <alloca.h> /* stdlib.h might not have obliged. */
Line 518:
printf("Semordnilap pairs: %d\n", sem);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 529:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Net;
using System.Collections.Generic;
Line 567:
private static string Reversed(string value) => new string(value.Reverse().ToArray());
}</langsyntaxhighlight>
{{out}}
<pre>
Line 579:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <fstream>
#include <iostream>
#include <set>
Line 606:
} else
return 1; // couldn't open input file
}</langsyntaxhighlight>
{{out}}
<pre>
Line 619:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns rosettacode.semordnilaps
(:require [clojure.string :as str])
[clojure.java.io :as io ]))
Line 642:
dict-file)
 
(dorun (->> semordnilaps shuffle (take 5) sort (map println)))</langsyntaxhighlight>
 
{{out}}
Line 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 673:
for word in words
do (print word)))
(values))</langsyntaxhighlight>
{{out}}
<pre>* (main)
Line 684:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">require "set"
 
UNIXDICT = File.read("unixdict.txt").lines
Line 701:
# print out the size, and 5 random pairs
puts final_results.size, final_results.sample(5)
</syntaxhighlight>
</lang>
 
{{out}}
Line 711:
=={{header|D}}==
===Simple Imperative Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.file, std.string, std.algorithm;
 
Line 729:
 
writeln("\nSemordnilap pairs: ", pairCount);
}</langsyntaxhighlight>
{{out}}
<pre>ca ac
Line 740:
 
===A More Functional Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.file, std.algorithm, std.string, std.range;
 
Line 748:
.zip(0.repeat).assocArray;
writeln(pairs.length, "\n", pairs.byKey.take(5));
}</langsyntaxhighlight>
{{out}}
<pre>158
Line 757:
{{libheader| System.StrUtils}}
{{libheader| System.Diagnostics}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Semordnilap;
 
Line 879:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 899:
We use the '''words''' library, and the french dictionary delivered with EchoLisp.
 
<langsyntaxhighlight lang="scheme">
(lib 'struct)
(lib 'sql)
Line 931:
longest → (rengager tresser strasse reveler retrace)
 
</syntaxhighlight>
</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 1,016:
 
end
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,053:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,065:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">words = File.stream!("unixdict.txt")
|> Enum.map(&String.strip/1)
|> Enum.group_by(&min(&1, String.reverse &1))
Line 1,071:
|> Enum.filter(&(length &1) == 2)
IO.puts "Semordnilap pair: #{length(words)}"
IO.inspect Enum.take(words,5)</langsyntaxhighlight>
 
{{out}}
Line 1,082:
=={{header|Erlang}}==
{{trans|Clojure}}
<langsyntaxhighlight lang="erlang">#!/usr/bin/env escript
main([]) -> main(["unixdict.txt"]);
 
Line 1,116:
[X||{_,X} <- lists:sort([ {random:uniform(), N} || N <- List])].
 
chop(L) -> [_|T] = lists:reverse(L), lists:reverse(T).</langsyntaxhighlight>
 
{{out}}
Line 1,128:
=={{header|F_Sharp|F#}}==
Using a mutable dictionary.
<langsyntaxhighlight lang="fsharp">open System
 
let seen = new System.Collections.Generic.Dictionary<string,bool>()
Line 1,144:
let s = Seq.toList sems
printfn "%d" s.Length
for i in 0 .. 4 do printfn "%A" s.[i]</langsyntaxhighlight>
{{out}}
<pre>158
Line 1,154:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs combinators.short-circuit formatting
io.encodings.utf8 io.files kernel literals locals make
prettyprint random sequences ;
Line 1,174:
]
] H{ } make >alist
[ length "%d semordnilap pairs.\n" printf ] [ 5 sample . ] bi</langsyntaxhighlight>
{{out}}
<pre>
Line 1,201:
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,237:
0 ' nt-semicheck dict traverse-wordlist cr .
cr bye
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,255:
 
 
<langsyntaxhighlight lang="fortran">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 21:50:08
Line 1,373:
 
end program Semordnilap
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight FreeBASIClang="freebasic">' version 20-06-2015
' compile with: fbc -s console
 
Line 1,455:
Print : Print "Hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Start reading unixdict.txt ... Done
Line 1,472:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,529:
fmt.Println(" ", e)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,542:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def semordnilapWords(source) {
def words = [] as Set
def semordnilaps = []
Line 1,550:
}
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,564:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import qualified Data.Set as S
 
semordnilaps
Line 1,580:
let l = semordnilaps (lines s)
print $ length l
mapM_ (print . ((,) <*> reverse)) $ take 5 (filter ((4 <) . length) l)</langsyntaxhighlight>
{{out}}
<pre>158
Line 1,592:
 
The following solution works in both Icon and Unicon:
<langsyntaxhighlight lang="unicon">procedure main(a)
words := set()
found := 0
Line 1,603:
write("\nFound ",found," semordnilap words")
end
</syntaxhighlight>
</lang>
 
Sample run with unixdict:
Line 1,622:
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,631:
Here's 5 of them, picked arbitrarily:
 
<syntaxhighlight lang="text"> (5?.158) { semordnilaps
┌────┬────┐
│kay │yak │
Line 1,642:
├────┼────┤
│caw │wac │
└────┴────┘</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|D}}
{{works with|Java|7+}}
<langsyntaxhighlight lang="java5">import java.nio.file.*;
import java.util.*;
 
Line 1,666:
System.out.println("\nSemordnilap pairs found: " + count);
}
}</langsyntaxhighlight>
<pre>ca ac
dab bad
Line 1,678:
===Node.js===
{{trans|Clojure}}
<langsyntaxhighlight lang="javascript">#!/usr/bin/env node
var fs = require('fs');
var sys = require('sys');
Line 1,717:
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,759:
for (var i=0; i<5; ++i) {
print(semordnilaps[indices[i]]);
}</langsyntaxhighlight>
 
{{out}}
Line 1,771:
===macOS JavaScript for Automation===
{{Trans|Python}}
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,830:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>158
Line 1,852:
* 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,863:
| (. < $rev and $dict[$rev]) );
 
[report] | (.[0:5][], "length = \(length)")</langsyntaxhighlight>
{{Out}}
able
Line 1,873:
 
=={{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,890:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.io.File
Line 1,900:
println("Found ${pairs.size} semordnilap pairs")
println(pairs.take(5))
}</langsyntaxhighlight>
 
{{out}}
Line 1,909:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 1,980:
done
done
echo ; print ${j} pairs found.</langsyntaxhighlight>
{{out}}<pre>
Examples:
Line 1,992:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(
words = string(include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt')) -> split('\n'),
semordnilaps = array,
Line 2,020:
#found_size
'<br />'
#examples</langsyntaxhighlight>
{{out}}
<pre>Total found: 158
Line 2,026:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print "Loading dictionary."
open "unixdict.txt" for input as #1
Line 2,071:
Next i
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,084:
 
=={{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 2,117:
semordnilaps[j] = nil
print(f .. " -> " .. r)
end</langsyntaxhighlight>
 
{{out}}
Line 2,128:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module semordnilaps {
Document d$
Line 2,155:
}
semordnilaps
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 2,167:
 
=={{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 2,176:
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight lang="nanoquery">import Nanoquery.IO
 
def reverse_str(string)
Line 2,204:
end
 
println "\nSemordnilap pairs found: " + count</langsyntaxhighlight>
{{out}}
<pre>ca ac
Line 2,216:
=={{header|NetRexx}}==
{{Trans|REXX}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,245:
Say pi 'words in' fid 'have a palindrome' /* total number found */
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,257:
 
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
<lang NewLisp>
;;; Get the words as a list, splitting at newline
(setq data
Line 2,284:
(dolist (x res)
(if (> (length x) 4) (println x " -- " (get-reverse x))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,297:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils, sequtils, sets, algorithm
 
proc reversed(s: string): string =
Line 2,312:
echo "Total number of semordnilaps: ", pairs.len
pairs = pairs.sortedByIt(it[0].len)
echo pairs[^5..^1]</langsyntaxhighlight>
 
{{out}}
Line 2,319:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">module StrSet = Set.Make(String)
 
let str_rev s =
Line 2,352:
let (word, rev) = List.nth pairs (Random.int len) in
Printf.printf " %s %s\n" word rev
done</langsyntaxhighlight>
 
{{out}}
Line 2,365:
 
=={{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,383:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: semordnilap
| w wr wrds |
ListBuffer new ->wrds
Line 2,390:
wrds include(w reverse dup ->wr) ifTrue: [ [wr, w] over add ]
w wr < ifTrue: [ wrds add(w) ]
] ;</langsyntaxhighlight>
 
{{out}}
Line 2,400:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">while (<>) {
chomp;
my $r = reverse;
Line 2,406:
}
 
print "$c\n"</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 2,422:
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,435:
=={{header|PHP}}==
{{trans|Raku}}
<langsyntaxhighlight lang="php"><?php
// Read dictionary into array
$dictionary = array_fill_keys(file(
Line 2,449:
// array_rand() returns keys, not values
foreach (array_rand($words, 5) as $word)
echo "$word $words[$word]\n";</langsyntaxhighlight>
{{out}}
<pre>158
Line 2,459:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Semordnilap
(mapcon
'((Lst)
Line 2,465:
(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,512:
end;
end find;
</syntaxhighlight>
</lang>
<pre>
There are 158 pairs.
Line 2,526:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Reverse-String ([string]$String)
{
Line 2,562:
 
"`nSemordnilap count: {0}" -f ($semordnilap.GetEnumerator() | Measure-Object).Count
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,582:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole("")=0 : End 1 : EndIf
If ReadFile(0,"./Data/unixdict.txt")=0 : End 2 : EndIf
NewList dict$()
Line 2,605:
PrintN(Space(15)+StringField(res$,k,#LF$))
Next
Input()</langsyntaxhighlight>
{{out}}
<pre>Semordnilap pairs found: 158
Line 2,617:
=={{header|Python}}==
===Idiomatic===
<langsyntaxhighlight lang="python">>>> with open('unixdict.txt') as f:
wordset = set(f.read().strip().split())
 
Line 2,627:
>>> sorted(pairs, key=lambda p: (len(p[0]), p))[-5:]
[('damon', 'nomad'), ('lager', 'regal'), ('leper', 'repel'), ('lever', 'revel'), ('kramer', 'remark')]
>>> </langsyntaxhighlight>
 
===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,742:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Dictionary words paired by equivalence under reversal:
Line 2,758:
Requires the <code>requests</code> library.
 
<langsyntaxhighlight lang="python">import sys
import random
import requests
Line 2,808:
if __name__ == '__main__':
main(*sys.argv[1:])
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,823:
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> []
<lang Quackery> []
$ "rosetta/unixdict.txt" sharefile drop
nest$
Line 2,839:
witheach
[ dup echo$ say "<->"
reverse echo$ sp ]</langsyntaxhighlight>
 
{{out}}
Line 2,849:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define seen (make-hash))
Line 2,864:
(for ([s (take (sort semordnilaps > #:key (compose1 string-length car)) 5)])
(apply printf " ~s ~s\n" s))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,880:
(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,887:
}
 
say $_ ~ ' ' ~ $_.flip for @sems.pick(5);</langsyntaxhighlight>
{{out}}
<pre>abut tuba
Line 2,897:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 07.09.2012 Walter Pachl
**********************************************************************/
Line 2,915:
End
End
Say pi 'words in' fid 'have a palindrome' /* total number found */</langsyntaxhighlight>
{{out}}
<pre>
Line 2,946:
 
The (first five) semordnilap pairs are shown as they are specified/defined (respective to case) in the dictionary.
<langsyntaxhighlight lang="rexx">/*REXX program finds N semordnilap pairs using a specified dictionary (UNIXDICT.TXT).*/
parse arg n iFID . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 5 /*Not specified? Then use the default.*/
Line 2,961:
end /*while*/ /*stick a fork in it, we're all done. */
say
say "There're " # ' unique semordnilap pairs in the dictionary file: ' iFID</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,974:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Semordnilap
 
Line 2,999:
nr = find(aList,bString)
return nr
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,012:
=={{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 3,019:
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 3,031:
 
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}}
<langsyntaxhighlight lang="rust">use std::collections::HashSet;
use std::fs::File;
use std::io::{self, BufRead};
Line 3,072:
Err(error) => eprintln!("{}", error),
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,085:
</pre>
===A Shortened Version===
<langsyntaxhighlight Rustlang="rust">use std::{collections::HashSet, fs};
 
fn reverse(x: &str) -> String {
Line 3,102:
println!("{}, {}", candidats[ind], reverse(candidats[ind]));
}
}</langsyntaxhighlight>
{{out}}
<pre>Numbers of pairs found: 158
Line 3,112:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">val wordsAll =
scala.io.Source.
fromURL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").
Line 3,142:
println( s"${ss.size} matches, including: \n" )
println( ss.take(5).mkString( "\n" ) )
}</langsyntaxhighlight>
{{out}}
<pre>158 matches, including:
Line 3,154:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "gethttp.s7i";
 
Line 3,190:
writeln;
writeln("Semordnilap pairs: " <& count);
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,205:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var c = 0
var seen = Hash()
 
Line 3,215:
}
 
say c</langsyntaxhighlight>
{{out}}
<pre>
Line 3,229:
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
<syntaxhighlight lang="snobol4">
<lang SNOBOL4>
* Program: semordnilap.sbl
* To run: sbl semordnilap.sbl < unixdict.txt
Line 3,264:
output = 'The number of semordnilap pairs is: ' outcount
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,278:
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">set seed 17760704
import delimited http://www.puzzlers.org/pub/wordlists/unixdict.txt, clear
save temp, replace
Line 3,295:
| 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 3,310:
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 3,320:
drib bird
eros sore
</syntaxhighlight>
</lang>
 
This seems wrong, but perhaps the test file has changed?
Line 3,326:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">guard let data = try? String(contentsOfFile: "unixdict.txt") else {
fatalError()
}
Line 3,336:
 
print("Found \(pairs.count) pairs")
print("Five examples: \(pairs.prefix(5))")</langsyntaxhighlight>
 
{{out}}
Line 3,344:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require http
 
Line 3,373:
puts "Example: $pair"
if {[incr i]>=5} break
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,385:
 
=={{header|Transd}}==
<langsyntaxhighlight Schemelang="scheme">#lang transd
 
MainModule: {
Line 3,402:
(lout "Random five: " Range(in: v 0 5))))
)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,410:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
Line 3,434:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,447:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
Line 3,484:
Set objUnixDict = Nothing
Set objSemordnilap = Nothing
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,497:
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">import "io" for File
 
var dict = File.read("unixdict.txt").split("\n")
Line 3,517:
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])")</langsyntaxhighlight>
 
{{out}}
Line 3,539:
 
=={{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,598:
];
IntOut(0, Count); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,611:
 
=={{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,619:
 
ss.len().println(); //--> 158
ss.shuffle()[0,5].println();</langsyntaxhighlight>
{{out}}
<pre>
10,339

edits