Semordnilap: Difference between revisions

Content added Content deleted
No edit summary
m (syntax highlighting fixup automation)
Line 18: Line 18:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V wordset = Set(File(‘unixdict.txt’).read().split("\n"))
<syntaxhighlight lang="11l">V wordset = Set(File(‘unixdict.txt’).read().split("\n"))
V revlist = wordset.map(word -> reversed(word))
V revlist = wordset.map(word -> reversed(word))
V pairs = Set(zip(wordset, revlist).filter((wrd, rev) -> wrd < rev & rev C :wordset))
V pairs = Set(zip(wordset, revlist).filter((wrd, rev) -> wrd < rev & rev C :wordset))


print(pairs.len)
print(pairs.len)
print(sorted(Array(pairs), key' p -> (p[0].len, p))[(len)-5..])</lang>
print(sorted(Array(pairs), key' p -> (p[0].len, p))[(len)-5..])</syntaxhighlight>


{{out}}
{{out}}
Line 33: Line 33:
=={{header|8th}}==
=={{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:
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
[] var, results


Line 51: Line 51:
a:shuffle
a:shuffle
( a:shift dup . " is the reverse of " . s:rev . cr ) 5 times bye
( a:shift dup . " is the reverse of " . s:rev . cr ) 5 times bye
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 67: 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:
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:


<lang Ada>with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;


package String_Vectors is
package String_Vectors is
Line 85: Line 85:
-- checks if Word is in List(Start .. Stop);
-- checks if Word is in List(Start .. Stop);
-- requirement: the words in List are sorted alphabetically
-- requirement: the words in List are sorted alphabetically
end String_Vectors;</lang>
end String_Vectors;</syntaxhighlight>


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:
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:


<lang Ada>package body String_Vectors is
<syntaxhighlight lang="ada">package body String_Vectors is


function Is_In(List: Vec;
function Is_In(List: Vec;
Line 123: Line 123:
end Read;
end Read;


end String_Vectors;</lang>
end String_Vectors;</syntaxhighlight>


This is the main program:
This is the main program:


<lang Ada>with String_Vectors, Ada.Text_IO, Ada.Command_Line;
<syntaxhighlight lang="ada">with String_Vectors, Ada.Text_IO, Ada.Command_Line;


procedure Semordnilap is
procedure Semordnilap is
Line 156: Line 156:
Ada.Text_IO.New_Line;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("pairs found:" & Integer'Image(Semi_Counter));
Ada.Text_IO.Put("pairs found:" & Integer'Image(Semi_Counter));
end Semordnilap;</lang>
end Semordnilap;</syntaxhighlight>


{{out}}
{{out}}
Line 169: Line 169:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>integer p, z;
<syntaxhighlight lang="aime">integer p, z;
record r;
record r;
file f;
file f;
Line 189: Line 189:
}
}


o_form("Semordnilap pairs: ~\n", p);</lang>
o_form("Semordnilap pairs: ~\n", p);</syntaxhighlight>
{{out}}
{{out}}
<pre>ca ac
<pre>ca ac
Line 201: Line 201:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{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.
The Algol 68 G "read" PRAGMA is used to include the associative array code from Associative_array/Iteration.
<lang algol68># find the semordnilaps in a list of words #
<syntaxhighlight lang="algol68"># find the semordnilaps in a list of words #
# use the associative array in the Associate array/iteration task #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
PR read "aArray.a68" PR
Line 262: Line 262:
close( input file );
close( input file );
print( ( whole( semordnilap count, 0 ), " semordnilaps found", newline ) )
print( ( whole( semordnilap count, 0 ), " semordnilaps found", newline ) )
FI</lang>
FI</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 274: Line 274:


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>words: read.lines "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
<syntaxhighlight lang="rebol">words: read.lines "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
pairs: []
pairs: []
loop words 'wrd [
loop words 'wrd [
Line 286: Line 286:
unique 'pairs
unique 'pairs


print map 1..5 => [sample pairs]</lang>
print map 1..5 => [sample pairs]</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
{{works with|AutoHotkey_L}}
<lang AutoHotkey>S := [], M := []
<syntaxhighlight lang="autohotkey">S := [], M := []


FileRead, dict, unixdict.txt
FileRead, dict, unixdict.txt
Line 311: Line 311:
r := A_LoopField . r
r := A_LoopField . r
return r
return r
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>5 Examples:
<pre>5 Examples:
Line 324: Line 324:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SEMORDNILAP.AWK unixdict.txt
# syntax: GAWK -f SEMORDNILAP.AWK unixdict.txt
{ arr[$0]++ }
{ arr[$0]++ }
Line 345: Line 345:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 358: Line 358:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> INSTALL @lib$+"SORTLIB"
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Sort% = FN_sortinit(0,0)
Line 407: Line 407:
SWAP P%?I%, L%?(P%-I%)
SWAP P%?I%, L%?(P%-I%)
NEXT
NEXT
= A$</lang>
= A$</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 419: Line 419:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang Bracmat>( get'("unixdict.txt",STR):?dict
<syntaxhighlight lang="bracmat">( get'("unixdict.txt",STR):?dict
& new$hash:?H
& new$hash:?H
& 0:?p
& 0:?p
Line 442: Line 442:
& out$(semordnilap !N dnuoF)
& out$(semordnilap !N dnuoF)
)
)
);</lang>
);</syntaxhighlight>
{{out}}
{{out}}
<pre>tv vt
<pre>tv vt
Line 453: Line 453:
=={{header|C}}==
=={{header|C}}==


<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <alloca.h> /* stdlib.h might not have obliged. */
#include <alloca.h> /* stdlib.h might not have obliged. */
Line 518: Line 518:
printf("Semordnilap pairs: %d\n", sem);
printf("Semordnilap pairs: %d\n", sem);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 529: Line 529:


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Net;
using System.Net;
using System.Collections.Generic;
using System.Collections.Generic;
Line 567: Line 567:
private static string Reversed(string value) => new string(value.Reverse().ToArray());
private static string Reversed(string value) => new string(value.Reverse().ToArray());
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 579: Line 579:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <fstream>
<syntaxhighlight lang="cpp">#include <fstream>
#include <iostream>
#include <iostream>
#include <set>
#include <set>
Line 606: Line 606:
} else
} else
return 1; // couldn't open input file
return 1; // couldn't open input file
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 619: Line 619:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(ns rosettacode.semordnilaps
<syntaxhighlight lang="clojure">(ns rosettacode.semordnilaps
(:require [clojure.string :as str])
(:require [clojure.string :as str])
[clojure.java.io :as io ]))
[clojure.java.io :as io ]))
Line 642: Line 642:
dict-file)
dict-file)


(dorun (->> semordnilaps shuffle (take 5) sort (map println)))</lang>
(dorun (->> semordnilaps shuffle (take 5) sort (map println)))</syntaxhighlight>


{{out}}
{{out}}
Line 653: Line 653:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun semordnilaps (word-list)
<syntaxhighlight lang="lisp">(defun semordnilaps (word-list)
(let ((word-map (make-hash-table :test 'equal)))
(let ((word-map (make-hash-table :test 'equal)))
(loop for word in word-list do
(loop for word in word-list do
Line 673: Line 673:
for word in words
for word in words
do (print word)))
do (print word)))
(values))</lang>
(values))</syntaxhighlight>
{{out}}
{{out}}
<pre>* (main)
<pre>* (main)
Line 684: Line 684:


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang ruby>require "set"
<syntaxhighlight lang="ruby">require "set"


UNIXDICT = File.read("unixdict.txt").lines
UNIXDICT = File.read("unixdict.txt").lines
Line 701: Line 701:
# print out the size, and 5 random pairs
# print out the size, and 5 random pairs
puts final_results.size, final_results.sample(5)
puts final_results.size, final_results.sample(5)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 711: Line 711:
=={{header|D}}==
=={{header|D}}==
===Simple Imperative Version===
===Simple Imperative Version===
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.file, std.string, std.algorithm;
import std.stdio, std.file, std.string, std.algorithm;


Line 729: Line 729:


writeln("\nSemordnilap pairs: ", pairCount);
writeln("\nSemordnilap pairs: ", pairCount);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>ca ac
<pre>ca ac
Line 740: Line 740:


===A More Functional Version===
===A More Functional Version===
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.file, std.algorithm, std.string, std.range;
import std.stdio, std.file, std.algorithm, std.string, std.range;


Line 748: Line 748:
.zip(0.repeat).assocArray;
.zip(0.repeat).assocArray;
writeln(pairs.length, "\n", pairs.byKey.take(5));
writeln(pairs.length, "\n", pairs.byKey.take(5));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>158
<pre>158
Line 757: Line 757:
{{libheader| System.StrUtils}}
{{libheader| System.StrUtils}}
{{libheader| System.Diagnostics}}
{{libheader| System.Diagnostics}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Semordnilap;
program Semordnilap;


Line 879: Line 879:
end.
end.


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 899: Line 899:
We use the '''words''' library, and the french dictionary delivered with EchoLisp.
We use the '''words''' library, and the french dictionary delivered with EchoLisp.


<lang scheme>
<syntaxhighlight lang="scheme">
(lib 'struct)
(lib 'struct)
(lib 'sql)
(lib 'sql)
Line 931: Line 931:
longest → (rengager tresser strasse reveler retrace)
longest → (rengager tresser strasse reveler retrace)


</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
First the programm reads the wordlist into an array.
First the programm reads the wordlist into an array.
Then it mirrors each word and searchs for it across the array using binary search.
Then it mirrors each word and searchs for it across the array using binary search.
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
SEMORDNILAP
SEMORDNILAP
Line 1,016: Line 1,016:


end
end
</syntaxhighlight>
</lang>
Test:
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 1,053: Line 1,053:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,065: Line 1,065:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>words = File.stream!("unixdict.txt")
<syntaxhighlight lang="elixir">words = File.stream!("unixdict.txt")
|> Enum.map(&String.strip/1)
|> Enum.map(&String.strip/1)
|> Enum.group_by(&min(&1, String.reverse &1))
|> Enum.group_by(&min(&1, String.reverse &1))
Line 1,071: Line 1,071:
|> Enum.filter(&(length &1) == 2)
|> Enum.filter(&(length &1) == 2)
IO.puts "Semordnilap pair: #{length(words)}"
IO.puts "Semordnilap pair: #{length(words)}"
IO.inspect Enum.take(words,5)</lang>
IO.inspect Enum.take(words,5)</syntaxhighlight>


{{out}}
{{out}}
Line 1,082: Line 1,082:
=={{header|Erlang}}==
=={{header|Erlang}}==
{{trans|Clojure}}
{{trans|Clojure}}
<lang erlang>#!/usr/bin/env escript
<syntaxhighlight lang="erlang">#!/usr/bin/env escript
main([]) -> main(["unixdict.txt"]);
main([]) -> main(["unixdict.txt"]);


Line 1,116: Line 1,116:
[X||{_,X} <- lists:sort([ {random:uniform(), N} || N <- List])].
[X||{_,X} <- lists:sort([ {random:uniform(), N} || N <- List])].


chop(L) -> [_|T] = lists:reverse(L), lists:reverse(T).</lang>
chop(L) -> [_|T] = lists:reverse(L), lists:reverse(T).</syntaxhighlight>


{{out}}
{{out}}
Line 1,128: Line 1,128:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
Using a mutable dictionary.
Using a mutable dictionary.
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let seen = new System.Collections.Generic.Dictionary<string,bool>()
let seen = new System.Collections.Generic.Dictionary<string,bool>()
Line 1,144: Line 1,144:
let s = Seq.toList sems
let s = Seq.toList sems
printfn "%d" s.Length
printfn "%d" s.Length
for i in 0 .. 4 do printfn "%A" s.[i]</lang>
for i in 0 .. 4 do printfn "%A" s.[i]</syntaxhighlight>
{{out}}
{{out}}
<pre>158
<pre>158
Line 1,154: Line 1,154:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: assocs combinators.short-circuit formatting
<syntaxhighlight lang="factor">USING: assocs combinators.short-circuit formatting
io.encodings.utf8 io.files kernel literals locals make
io.encodings.utf8 io.files kernel literals locals make
prettyprint random sequences ;
prettyprint random sequences ;
Line 1,174: Line 1,174:
]
]
] H{ } make >alist
] H{ } make >alist
[ length "%d semordnilap pairs.\n" printf ] [ 5 sample . ] bi</lang>
[ length "%d semordnilap pairs.\n" printf ] [ 5 sample . ] bi</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,201: 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).
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).


<lang forth>
<syntaxhighlight lang="forth">
wordlist constant dict
wordlist constant dict


Line 1,237: Line 1,237:
0 ' nt-semicheck dict traverse-wordlist cr .
0 ' nt-semicheck dict traverse-wordlist cr .
cr bye
cr bye
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,255: Line 1,255:




<lang fortran>
<syntaxhighlight lang="fortran">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun May 19 21:50:08
!Compilation started at Sun May 19 21:50:08
Line 1,373: Line 1,373:


end program Semordnilap
end program Semordnilap
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang FreeBASIC>' version 20-06-2015
<syntaxhighlight lang="freebasic">' version 20-06-2015
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,455: Line 1,455:
Print : Print "Hit any key to end program"
Print : Print "Hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>Start reading unixdict.txt ... Done
<pre>Start reading unixdict.txt ... Done
Line 1,472: Line 1,472:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,529: Line 1,529:
fmt.Println(" ", e)
fmt.Println(" ", e)
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,542: Line 1,542:


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def semordnilapWords(source) {
<syntaxhighlight lang="groovy">def semordnilapWords(source) {
def words = [] as Set
def words = [] as Set
def semordnilaps = []
def semordnilaps = []
Line 1,550: Line 1,550:
}
}
semordnilaps
semordnilaps
}</lang>
}</syntaxhighlight>
Test Code
Test Code
<lang groovy>def semordnilaps = semordnilapWords(new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt'))
<syntaxhighlight lang="groovy">def semordnilaps = semordnilapWords(new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt'))
println "Found ${semordnilaps.size()} semordnilap words"
println "Found ${semordnilaps.size()} semordnilap words"
semordnilaps[0..<5].each { println "$it -> ${it.reverse()}" } </lang>
semordnilaps[0..<5].each { println "$it -> ${it.reverse()}" } </syntaxhighlight>
{{out}}
{{out}}
<pre>Found 158 semordnilap words
<pre>Found 158 semordnilap words
Line 1,564: Line 1,564:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import qualified Data.Set as S
<syntaxhighlight lang="haskell">import qualified Data.Set as S


semordnilaps
semordnilaps
Line 1,580: Line 1,580:
let l = semordnilaps (lines s)
let l = semordnilaps (lines s)
print $ length l
print $ length l
mapM_ (print . ((,) <*> reverse)) $ take 5 (filter ((4 <) . length) l)</lang>
mapM_ (print . ((,) <*> reverse)) $ take 5 (filter ((4 <) . length) l)</syntaxhighlight>
{{out}}
{{out}}
<pre>158
<pre>158
Line 1,592: Line 1,592:


The following solution works in both Icon and Unicon:
The following solution works in both Icon and Unicon:
<lang unicon>procedure main(a)
<syntaxhighlight lang="unicon">procedure main(a)
words := set()
words := set()
found := 0
found := 0
Line 1,603: Line 1,603:
write("\nFound ",found," semordnilap words")
write("\nFound ",found," semordnilap words")
end
end
</syntaxhighlight>
</lang>


Sample run with unixdict:
Sample run with unixdict:
Line 1,622: 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:
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:


<lang j> isSemordnilap=: |.&.> (~: *. e.) ]
<syntaxhighlight lang="j"> isSemordnilap=: |.&.> (~: *. e.) ]
unixdict=: <;._2 freads 'unixdict.txt'
unixdict=: <;._2 freads 'unixdict.txt'
#semordnilaps=: ~. /:~"1 (,. |.&.>) (#~ isSemordnilap) unixdict
#semordnilaps=: ~. /:~"1 (,. |.&.>) (#~ isSemordnilap) unixdict
158</lang>
158</syntaxhighlight>


We see that there are 158 semordnilaps.
We see that there are 158 semordnilaps.
Line 1,631: Line 1,631:
Here's 5 of them, picked arbitrarily:
Here's 5 of them, picked arbitrarily:


<lang> (5?.158) { semordnilaps
<syntaxhighlight lang="text"> (5?.158) { semordnilaps
┌────┬────┐
┌────┬────┐
│kay │yak │
│kay │yak │
Line 1,642: Line 1,642:
├────┼────┤
├────┼────┤
│caw │wac │
│caw │wac │
└────┴────┘</lang>
└────┴────┘</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{trans|D}}
{{trans|D}}
{{works with|Java|7+}}
{{works with|Java|7+}}
<lang java5>import java.nio.file.*;
<syntaxhighlight lang="java5">import java.nio.file.*;
import java.util.*;
import java.util.*;


Line 1,666: Line 1,666:
System.out.println("\nSemordnilap pairs found: " + count);
System.out.println("\nSemordnilap pairs found: " + count);
}
}
}</lang>
}</syntaxhighlight>
<pre>ca ac
<pre>ca ac
dab bad
dab bad
Line 1,678: Line 1,678:
===Node.js===
===Node.js===
{{trans|Clojure}}
{{trans|Clojure}}
<lang javascript>#!/usr/bin/env node
<syntaxhighlight lang="javascript">#!/usr/bin/env node
var fs = require('fs');
var fs = require('fs');
var sys = require('sys');
var sys = require('sys');
Line 1,717: Line 1,717:
for (var i=0; i<5; ++i) {
for (var i=0; i<5; ++i) {
sys.puts(semordnilaps[indices[i]]);
sys.puts(semordnilaps[indices[i]]);
}</lang>
}</syntaxhighlight>


===Rhino===
===Rhino===
{{works with|Rhino|1.7}}
{{works with|Rhino|1.7}}


<lang javascript>#!/usr/bin/env rhino
<syntaxhighlight lang="javascript">#!/usr/bin/env rhino


importPackage (java.io)
importPackage (java.io)
Line 1,759: Line 1,759:
for (var i=0; i<5; ++i) {
for (var i=0; i<5; ++i) {
print(semordnilaps[indices[i]]);
print(semordnilaps[indices[i]]);
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,771: Line 1,771:
===macOS JavaScript for Automation===
===macOS JavaScript for Automation===
{{Trans|Python}}
{{Trans|Python}}
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,830: Line 1,830:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>158
<pre>158
Line 1,852: Line 1,852:
* time /usr/local/bin/jq -M -s -R -r -f semordnilap.jq unixdict.txt
* time /usr/local/bin/jq -M -s -R -r -f semordnilap.jq unixdict.txt
user 0m0.440s; sys 0m0.010s
user 0m0.440s; sys 0m0.010s
<syntaxhighlight lang="jq">
<lang jq>
# Produce a stream
# Produce a stream
def report:
def report:
Line 1,863: Line 1,863:
| (. < $rev and $dict[$rev]) );
| (. < $rev and $dict[$rev]) );


[report] | (.[0:5][], "length = \(length)")</lang>
[report] | (.[0:5][], "length = \(length)")</syntaxhighlight>
{{Out}}
{{Out}}
able
able
Line 1,873: Line 1,873:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>raw = readdlm("unixdict.txt",String)[:]
<syntaxhighlight lang="julia">raw = readdlm("unixdict.txt",String)[:]
inter = intersect(raw,map(reverse,raw)) #find the matching strings/revstrings
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 = 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</lang>
res = res[res[:,1] .!= res[:,2],:] #get rid of duplicates, palindromes</syntaxhighlight>
<pre>julia> length(res[:,1])
<pre>julia> length(res[:,1])
158
158
Line 1,890: Line 1,890:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|D}}
{{trans|D}}
<lang scala>// version 1.2.0
<syntaxhighlight lang="scala">// version 1.2.0


import java.io.File
import java.io.File
Line 1,900: Line 1,900:
println("Found ${pairs.size} semordnilap pairs")
println("Found ${pairs.size} semordnilap pairs")
println(pairs.take(5))
println(pairs.take(5))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,909: Line 1,909:


=={{header|Ksh}}==
=={{header|Ksh}}==
<lang ksh>
<syntaxhighlight lang="ksh">
#!/bin/ksh
#!/bin/ksh


Line 1,980: Line 1,980:
done
done
done
done
echo ; print ${j} pairs found.</lang>
echo ; print ${j} pairs found.</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
Examples:
Examples:
Line 1,992: Line 1,992:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(
<syntaxhighlight lang="lasso">local(
words = string(include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt')) -> split('\n'),
words = string(include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt')) -> split('\n'),
semordnilaps = array,
semordnilaps = array,
Line 2,020: Line 2,020:
#found_size
#found_size
'<br />'
'<br />'
#examples</lang>
#examples</syntaxhighlight>
{{out}}
{{out}}
<pre>Total found: 158
<pre>Total found: 158
Line 2,026: Line 2,026:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print "Loading dictionary."
print "Loading dictionary."
open "unixdict.txt" for input as #1
open "unixdict.txt" for input as #1
Line 2,071: Line 2,071:
Next i
Next i
End Function
End Function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,084: Line 2,084:


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>#!/usr/bin/env lua
<syntaxhighlight lang="lua">#!/usr/bin/env lua
-- allow dictionary file and sample size to be specified on command line
-- allow dictionary file and sample size to be specified on command line
local dictfile = arg[1] or "unixdict.txt"
local dictfile = arg[1] or "unixdict.txt"
Line 2,117: Line 2,117:
semordnilaps[j] = nil
semordnilaps[j] = nil
print(f .. " -> " .. r)
print(f .. " -> " .. r)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,128: Line 2,128:


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module semordnilaps {
Module semordnilaps {
Document d$
Document d$
Line 2,155: Line 2,155:
}
}
semordnilaps
semordnilaps
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height:30ex;overflow:scroll">
<pre style="height:30ex;overflow:scroll">
Line 2,167: Line 2,167:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>data = Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"];
<syntaxhighlight lang="mathematica">data = Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"];
result = DeleteDuplicates[ Select[data, MemberQ[data, StringReverse[#]]
result = DeleteDuplicates[ Select[data, MemberQ[data, StringReverse[#]]
&& # =!= StringReverse[#] &], (# ===StringReverse[#2]) &];
&& # =!= StringReverse[#] &], (# ===StringReverse[#2]) &];
Print[Length[result], Take[result, 5]]</lang>
Print[Length[result], Take[result, 5]]</syntaxhighlight>
{{out}}
{{out}}
<pre>158 {able,abut,ac,ah,al}</pre>
<pre>158 {able,abut,ac,ah,al}</pre>
Line 2,176: Line 2,176:
=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Java}}
{{trans|Java}}
<lang nanoquery>import Nanoquery.IO
<syntaxhighlight lang="nanoquery">import Nanoquery.IO


def reverse_str(string)
def reverse_str(string)
Line 2,204: Line 2,204:
end
end


println "\nSemordnilap pairs found: " + count</lang>
println "\nSemordnilap pairs found: " + count</syntaxhighlight>
{{out}}
{{out}}
<pre>ca ac
<pre>ca ac
Line 2,216: Line 2,216:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{Trans|REXX}}
{{Trans|REXX}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,245: Line 2,245:
Say pi 'words in' fid 'have a palindrome' /* total number found */
Say pi 'words in' fid 'have a palindrome' /* total number found */
return
return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,257: Line 2,257:


=={{header|NewLisp}}==
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
<lang NewLisp>
;;; Get the words as a list, splitting at newline
;;; Get the words as a list, splitting at newline
(setq data
(setq data
Line 2,284: Line 2,284:
(dolist (x res)
(dolist (x res)
(if (> (length x) 4) (println x " -- " (get-reverse x))))
(if (> (length x) 4) (println x " -- " (get-reverse x))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,297: Line 2,297:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils, sequtils, sets, algorithm
<syntaxhighlight lang="nim">import strutils, sequtils, sets, algorithm


proc reversed(s: string): string =
proc reversed(s: string): string =
Line 2,312: Line 2,312:
echo "Total number of semordnilaps: ", pairs.len
echo "Total number of semordnilaps: ", pairs.len
pairs = pairs.sortedByIt(it[0].len)
pairs = pairs.sortedByIt(it[0].len)
echo pairs[^5..^1]</lang>
echo pairs[^5..^1]</syntaxhighlight>


{{out}}
{{out}}
Line 2,319: Line 2,319:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>module StrSet = Set.Make(String)
<syntaxhighlight lang="ocaml">module StrSet = Set.Make(String)


let str_rev s =
let str_rev s =
Line 2,352: Line 2,352:
let (word, rev) = List.nth pairs (Random.int len) in
let (word, rev) = List.nth pairs (Random.int len) in
Printf.printf " %s %s\n" word rev
Printf.printf " %s %s\n" word rev
done</lang>
done</syntaxhighlight>


{{out}}
{{out}}
Line 2,365: Line 2,365:


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>a = strsplit(fileread("unixdict.txt"), "\n");
<syntaxhighlight lang="octave">a = strsplit(fileread("unixdict.txt"), "\n");
a = intersect(a, cellfun(@fliplr, a, "UniformOutput", false));
a = intersect(a, cellfun(@fliplr, a, "UniformOutput", false));
a = a(arrayfun(@(i) ismember(fliplr(a{i}), a(i+1:length(a))), 1:length(a)));
a = a(arrayfun(@(i) ismember(fliplr(a{i}), a(i+1:length(a))), 1:length(a)));
length(a)
length(a)
arrayfun(@(i) printf("%s %s\n", a{i}, fliplr(a{i})), 1:5)</lang>
arrayfun(@(i) printf("%s %s\n", a{i}, fliplr(a{i})), 1:5)</syntaxhighlight>


'''Output:'''
'''Output:'''
Line 2,383: Line 2,383:
=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: semordnilap
<syntaxhighlight lang="oforth">: semordnilap
| w wr wrds |
| w wr wrds |
ListBuffer new ->wrds
ListBuffer new ->wrds
Line 2,390: Line 2,390:
wrds include(w reverse dup ->wr) ifTrue: [ [wr, w] over add ]
wrds include(w reverse dup ->wr) ifTrue: [ [wr, w] over add ]
w wr < ifTrue: [ wrds add(w) ]
w wr < ifTrue: [ wrds add(w) ]
] ;</lang>
] ;</syntaxhighlight>


{{out}}
{{out}}
Line 2,400: Line 2,400:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>while (<>) {
<syntaxhighlight lang="perl">while (<>) {
chomp;
chomp;
my $r = reverse;
my $r = reverse;
Line 2,406: Line 2,406:
}
}


print "$c\n"</lang>
print "$c\n"</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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: 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: #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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,435: Line 2,435:
=={{header|PHP}}==
=={{header|PHP}}==
{{trans|Raku}}
{{trans|Raku}}
<lang php><?php
<syntaxhighlight lang="php"><?php
// Read dictionary into array
// Read dictionary into array
$dictionary = array_fill_keys(file(
$dictionary = array_fill_keys(file(
Line 2,449: Line 2,449:
// array_rand() returns keys, not values
// array_rand() returns keys, not values
foreach (array_rand($words, 5) as $word)
foreach (array_rand($words, 5) as $word)
echo "$word $words[$word]\n";</lang>
echo "$word $words[$word]\n";</syntaxhighlight>
{{out}}
{{out}}
<pre>158
<pre>158
Line 2,459: Line 2,459:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(let Semordnilap
<syntaxhighlight lang="picolisp">(let Semordnilap
(mapcon
(mapcon
'((Lst)
'((Lst)
Line 2,465: Line 2,465:
(cons (pack (car Lst))) ) )
(cons (pack (car Lst))) ) )
(make (in "unixdict.txt" (while (line) (link @)))) )
(make (in "unixdict.txt" (while (line) (link @)))) )
(println (length Semordnilap) (head 5 Semordnilap)) )</lang>
(println (length Semordnilap) (head 5 Semordnilap)) )</syntaxhighlight>
{{out}}
{{out}}
<pre>158 ("able" "abut" "ac" "ah" "al")</pre>
<pre>158 ("able" "abut" "ac" "ah" "al")</pre>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
find: procedure options (main); /* 20/1/2013 */
find: procedure options (main); /* 20/1/2013 */
declare word character (20) varying controlled;
declare word character (20) varying controlled;
Line 2,512: Line 2,512:
end;
end;
end find;
end find;
</syntaxhighlight>
</lang>
<pre>
<pre>
There are 158 pairs.
There are 158 pairs.
Line 2,526: Line 2,526:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Reverse-String ([string]$String)
function Reverse-String ([string]$String)
{
{
Line 2,562: Line 2,562:


"`nSemordnilap count: {0}" -f ($semordnilap.GetEnumerator() | Measure-Object).Count
"`nSemordnilap count: {0}" -f ($semordnilap.GetEnumerator() | Measure-Object).Count
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 2,582: Line 2,582:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>If OpenConsole("")=0 : End 1 : EndIf
<syntaxhighlight lang="purebasic">If OpenConsole("")=0 : End 1 : EndIf
If ReadFile(0,"./Data/unixdict.txt")=0 : End 2 : EndIf
If ReadFile(0,"./Data/unixdict.txt")=0 : End 2 : EndIf
NewList dict$()
NewList dict$()
Line 2,605: Line 2,605:
PrintN(Space(15)+StringField(res$,k,#LF$))
PrintN(Space(15)+StringField(res$,k,#LF$))
Next
Next
Input()</lang>
Input()</syntaxhighlight>
{{out}}
{{out}}
<pre>Semordnilap pairs found: 158
<pre>Semordnilap pairs found: 158
Line 2,617: Line 2,617:
=={{header|Python}}==
=={{header|Python}}==
===Idiomatic===
===Idiomatic===
<lang python>>>> with open('unixdict.txt') as f:
<syntaxhighlight lang="python">>>> with open('unixdict.txt') as f:
wordset = set(f.read().strip().split())
wordset = set(f.read().strip().split())


Line 2,627: Line 2,627:
>>> sorted(pairs, key=lambda p: (len(p[0]), p))[-5:]
>>> sorted(pairs, key=lambda p: (len(p[0]), p))[-5:]
[('damon', 'nomad'), ('lager', 'regal'), ('leper', 'repel'), ('lever', 'revel'), ('kramer', 'remark')]
[('damon', 'nomad'), ('lager', 'regal'), ('leper', 'repel'), ('lever', 'revel'), ('kramer', 'remark')]
>>> </lang>
>>> </syntaxhighlight>


===As a fold, using reduce===
===As a fold, using reduce===
{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Dictionary words paired by equivalence under reversal'''
<syntaxhighlight lang="python">'''Dictionary words paired by equivalence under reversal'''


from functools import (reduce)
from functools import (reduce)
Line 2,742: Line 2,742:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Dictionary words paired by equivalence under reversal:
<pre>Dictionary words paired by equivalence under reversal:
Line 2,758: Line 2,758:
Requires the <code>requests</code> library.
Requires the <code>requests</code> library.


<lang python>import sys
<syntaxhighlight lang="python">import sys
import random
import random
import requests
import requests
Line 2,808: Line 2,808:
if __name__ == '__main__':
if __name__ == '__main__':
main(*sys.argv[1:])
main(*sys.argv[1:])
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 2,823: Line 2,823:
=={{header|Quackery}}==
=={{header|Quackery}}==


<syntaxhighlight lang="quackery"> []
<lang Quackery> []
$ "rosetta/unixdict.txt" sharefile drop
$ "rosetta/unixdict.txt" sharefile drop
nest$
nest$
Line 2,839: Line 2,839:
witheach
witheach
[ dup echo$ say "<->"
[ dup echo$ say "<->"
reverse echo$ sp ]</lang>
reverse echo$ sp ]</syntaxhighlight>


{{out}}
{{out}}
Line 2,849: Line 2,849:


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket
(define seen (make-hash))
(define seen (make-hash))
Line 2,864: Line 2,864:
(for ([s (take (sort semordnilaps > #:key (compose1 string-length car)) 5)])
(for ([s (take (sort semordnilaps > #:key (compose1 string-length car)) 5)])
(apply printf " ~s ~s\n" s))
(apply printf " ~s ~s\n" s))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,880: Line 2,880:
(formerly Perl 6)
(formerly Perl 6)
{{works with|rakudo|2015-10-26}}
{{works with|rakudo|2015-10-26}}
<lang perl6>my $words = set slurp("unixdict.txt").lines;
<syntaxhighlight lang="raku" line>my $words = set slurp("unixdict.txt").lines;


my @sems = gather for $words.flat -> $word {
my @sems = gather for $words.flat -> $word {
Line 2,887: Line 2,887:
}
}


say $_ ~ ' ' ~ $_.flip for @sems.pick(5);</lang>
say $_ ~ ' ' ~ $_.flip for @sems.pick(5);</syntaxhighlight>
{{out}}
{{out}}
<pre>abut tuba
<pre>abut tuba
Line 2,897: Line 2,897:
=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx>/* REXX ***************************************************************
<syntaxhighlight lang="rexx">/* REXX ***************************************************************
* 07.09.2012 Walter Pachl
* 07.09.2012 Walter Pachl
**********************************************************************/
**********************************************************************/
Line 2,915: Line 2,915:
End
End
End
End
Say pi 'words in' fid 'have a palindrome' /* total number found */</lang>
Say pi 'words in' fid 'have a palindrome' /* total number found */</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,946: Line 2,946:


The (first five) semordnilap pairs are shown as they are specified/defined (respective to case) in the dictionary.
The (first five) semordnilap pairs are shown as they are specified/defined (respective to case) in the dictionary.
<lang rexx>/*REXX program finds N semordnilap pairs using a specified dictionary (UNIXDICT.TXT).*/
<syntaxhighlight lang="rexx">/*REXX program finds N semordnilap pairs using a specified dictionary (UNIXDICT.TXT).*/
parse arg n iFID . /*obtain optional argument from the CL.*/
parse arg n iFID . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 5 /*Not specified? Then use the default.*/
if n=='' | n=="," then n= 5 /*Not specified? Then use the default.*/
Line 2,961: Line 2,961:
end /*while*/ /*stick a fork in it, we're all done. */
end /*while*/ /*stick a fork in it, we're all done. */
say
say
say "There're " # ' unique semordnilap pairs in the dictionary file: ' iFID</lang>
say "There're " # ' unique semordnilap pairs in the dictionary file: ' iFID</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 2,974: Line 2,974:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Semordnilap
# Project : Semordnilap


Line 2,999: Line 2,999:
nr = find(aList,bString)
nr = find(aList,bString)
return nr
return nr
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,012: Line 3,012:
=={{header|Ruby}}==
=={{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)
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)
<lang Ruby>dict = File.readlines("unixdict.txt").collect(&:strip)
<syntaxhighlight lang="ruby">dict = File.readlines("unixdict.txt").collect(&:strip)
i = 0
i = 0
res = dict.collect(&:reverse).sort.select do |z|
res = dict.collect(&:reverse).sort.select do |z|
Line 3,019: Line 3,019:
end
end
puts "There are #{res.length} semordnilaps, of which the following are 5:"
puts "There are #{res.length} semordnilaps, of which the following are 5:"
res.take(5).each {|z| puts "#{z} #{z.reverse}"}</lang>
res.take(5).each {|z| puts "#{z} #{z.reverse}"}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,031: Line 3,031:


Another way
Another way
<lang Ruby>words = File.readlines("unixdict.txt")
<syntaxhighlight lang="ruby">words = File.readlines("unixdict.txt")
.group_by{|x| [x.strip!, x.reverse].min}
.group_by{|x| [x.strip!, x.reverse].min}
.values
.values
.select{|v| v.size==2}
.select{|v| v.size==2}
puts "There are #{words.size} semordnilaps, of which the following are 5:"
puts "There are #{words.size} semordnilaps, of which the following are 5:"
words.take(5).each {|a,b| puts "#{a} #{b}"}</lang>
words.take(5).each {|a,b| puts "#{a} #{b}"}</syntaxhighlight>
output is the same above.
output is the same above.


=={{header|Rust}}==
=={{header|Rust}}==
{{trans|Java}}
{{trans|Java}}
<lang rust>use std::collections::HashSet;
<syntaxhighlight lang="rust">use std::collections::HashSet;
use std::fs::File;
use std::fs::File;
use std::io::{self, BufRead};
use std::io::{self, BufRead};
Line 3,072: Line 3,072:
Err(error) => eprintln!("{}", error),
Err(error) => eprintln!("{}", error),
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,085: Line 3,085:
</pre>
</pre>
===A Shortened Version===
===A Shortened Version===
<lang Rust>use std::{collections::HashSet, fs};
<syntaxhighlight lang="rust">use std::{collections::HashSet, fs};


fn reverse(x: &str) -> String {
fn reverse(x: &str) -> String {
Line 3,102: Line 3,102:
println!("{}, {}", candidats[ind], reverse(candidats[ind]));
println!("{}, {}", candidats[ind], reverse(candidats[ind]));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Numbers of pairs found: 158
<pre>Numbers of pairs found: 158
Line 3,112: Line 3,112:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>val wordsAll =
<syntaxhighlight lang="scala">val wordsAll =
scala.io.Source.
scala.io.Source.
fromURL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").
fromURL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").
Line 3,142: Line 3,142:
println( s"${ss.size} matches, including: \n" )
println( s"${ss.size} matches, including: \n" )
println( ss.take(5).mkString( "\n" ) )
println( ss.take(5).mkString( "\n" ) )
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>158 matches, including:
<pre>158 matches, including:
Line 3,154: Line 3,154:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "gethttp.s7i";
include "gethttp.s7i";


Line 3,190: Line 3,190:
writeln;
writeln;
writeln("Semordnilap pairs: " <& count);
writeln("Semordnilap pairs: " <& count);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 3,205: Line 3,205:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>var c = 0
<syntaxhighlight lang="ruby">var c = 0
var seen = Hash()
var seen = Hash()


Line 3,215: Line 3,215:
}
}


say c</lang>
say c</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,229: Line 3,229:
=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
{{works with|SNOBOL4, SPITBOL for Linux}}
<syntaxhighlight lang="snobol4">
<lang SNOBOL4>
* Program: semordnilap.sbl
* Program: semordnilap.sbl
* To run: sbl semordnilap.sbl < unixdict.txt
* To run: sbl semordnilap.sbl < unixdict.txt
Line 3,264: Line 3,264:
output = 'The number of semordnilap pairs is: ' outcount
output = 'The number of semordnilap pairs is: ' outcount
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,278: Line 3,278:
=={{header|Stata}}==
=={{header|Stata}}==


<lang stata>set seed 17760704
<syntaxhighlight lang="stata">set seed 17760704
import delimited http://www.puzzlers.org/pub/wordlists/unixdict.txt, clear
import delimited http://www.puzzlers.org/pub/wordlists/unixdict.txt, clear
save temp, replace
save temp, replace
Line 3,295: Line 3,295:
| nit tin |
| nit tin |
| ku uk |
| ku uk |
+-------------+</lang>
+-------------+</syntaxhighlight>


=={{header|SuperCollider}}==
=={{header|SuperCollider}}==
{{incorrect|SuperCollider|The number of pairs should be 158.}}
{{incorrect|SuperCollider|The number of pairs should be 158.}}
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
var text, words, sdrow, semordnilap, selection;
var text, words, sdrow, semordnilap, selection;
File.use("unixdict.txt".resolveRelative, "r", { |f| x = text = f.readAllString });
File.use("unixdict.txt".resolveRelative, "r", { |f| x = text = f.readAllString });
Line 3,310: Line 3,310:
selection = semordnilap.select { |each| each.size >= 4 }.scramble.keep(4);
selection = semordnilap.select { |each| each.size >= 4 }.scramble.keep(4);
selection.do { |each| "% %\n".postf(each, each.reverse); };
selection.do { |each| "% %\n".postf(each, each.reverse); };
)</lang>
)</syntaxhighlight>


Answers:
Answers:
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
There are 405 in unixdict.txt
There are 405 in unixdict.txt
For example those, with more than 3 characters:
For example those, with more than 3 characters:
Line 3,320: Line 3,320:
drib bird
drib bird
eros sore
eros sore
</syntaxhighlight>
</lang>


This seems wrong, but perhaps the test file has changed?
This seems wrong, but perhaps the test file has changed?
Line 3,326: Line 3,326:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>guard let data = try? String(contentsOfFile: "unixdict.txt") else {
<syntaxhighlight lang="swift">guard let data = try? String(contentsOfFile: "unixdict.txt") else {
fatalError()
fatalError()
}
}
Line 3,336: Line 3,336:


print("Found \(pairs.count) pairs")
print("Found \(pairs.count) pairs")
print("Five examples: \(pairs.prefix(5))")</lang>
print("Five examples: \(pairs.prefix(5))")</syntaxhighlight>


{{out}}
{{out}}
Line 3,344: Line 3,344:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require http
package require http


Line 3,373: Line 3,373:
puts "Example: $pair"
puts "Example: $pair"
if {[incr i]>=5} break
if {[incr i]>=5} break
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,385: Line 3,385:


=={{header|Transd}}==
=={{header|Transd}}==
<lang Scheme>#lang transd
<syntaxhighlight lang="scheme">#lang transd


MainModule: {
MainModule: {
Line 3,402: Line 3,402:
(lout "Random five: " Range(in: v 0 5))))
(lout "Random five: " Range(in: v 0 5))))
)
)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,410: Line 3,410:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
$$ MODE TUSCRIPT,{}
requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
Line 3,434: Line 3,434:
ENDLOOP
ENDLOOP
ENDCOMPILE
ENDCOMPILE
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,447: Line 3,447:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
Line 3,484: Line 3,484:
Set objUnixDict = Nothing
Set objUnixDict = Nothing
Set objSemordnilap = Nothing
Set objSemordnilap = Nothing
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,497: Line 3,497:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "io" for File
<syntaxhighlight lang="ecmascript">import "io" for File


var dict = File.read("unixdict.txt").split("\n")
var dict = File.read("unixdict.txt").split("\n")
Line 3,517: Line 3,517:
for (i in 0..4) System.print(" %(pairs[i][0]), %(pairs[i][1])")
for (i in 0..4) System.print(" %(pairs[i][0]), %(pairs[i][1])")
System.print("\nand the last five are:")
System.print("\nand the last five are:")
for (i in -5..-1) System.print(" %(pairs[i][0]), %(pairs[i][1])")</lang>
for (i in -5..-1) System.print(" %(pairs[i][0]), %(pairs[i][1])")</syntaxhighlight>


{{out}}
{{out}}
Line 3,539: Line 3,539:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
string 0; \use zero-terminated strings
def LF=$0A, CR=$0D, EOF=$1A;
def LF=$0A, CR=$0D, EOF=$1A;
Line 3,598: Line 3,598:
];
];
IntOut(0, Count); CrLf(0);
IntOut(0, Count); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 3,611: Line 3,611:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>var [const] words= // create hashed unixdict of striped words (word:True, ...)
<syntaxhighlight 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));
File("dict.txt").howza(11).pump(Dictionary().howza(8).add.fp1(True));
ss:=words.pump(List, // push stripped unixdict words through some functions
ss:=words.pump(List, // push stripped unixdict words through some functions
Line 3,619: Line 3,619:


ss.len().println(); //--> 158
ss.len().println(); //--> 158
ss.shuffle()[0,5].println();</lang>
ss.shuffle()[0,5].println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>