langs a-z

This commit is contained in:
Ingy döt Net 2013-04-10 22:43:41 -07:00
parent db842d013d
commit d066446780
11389 changed files with 98361 additions and 1020 deletions

View file

@ -0,0 +1,34 @@
let explode str =
let l = ref [] in
let len = String.length str in
for i = len - 1 downto 0 do
l := str.[i] :: !l
done;
(!l)
let implode li =
let len = List.length li in
let s = String.create len in
let i = ref 0 in
List.iter (fun c -> s.[!i] <- c; incr i) li;
(s)
let () =
let h = Hashtbl.create 3571 in
let ic = open_in "unixdict.txt" in
try while true do
let w = input_line ic in
let k = implode(List.sort compare (explode w)) in
let l =
try Hashtbl.find h k
with Not_found -> []
in
Hashtbl.add h k (w::l);
done with End_of_file -> ();
let n = Hashtbl.fold (fun _ lw n -> max n (List.length lw)) h 0 in
Hashtbl.iter (fun _ lw ->
if List.length lw >= n then
( List.iter (Printf.printf " %s") lw;
print_newline())
) h;
;;

View file

@ -0,0 +1,156 @@
MODULE Anagrams;
IMPORT Files,Out,In,Strings;
CONST
MAXPOOLSZ = 1024;
TYPE
String = ARRAY 80 OF CHAR;
Node = POINTER TO NodeDesc;
NodeDesc = RECORD;
count: INTEGER;
word: String;
desc: Node;
next: Node;
END;
Pool = POINTER TO PoolDesc;
PoolDesc = RECORD
capacity,max: INTEGER;
words: POINTER TO ARRAY OF Node;
END;
PROCEDURE InitNode(n: Node);
BEGIN
n^.count := 0;
n^.word := "";
n^.desc := NIL;
n^.next := NIL;
END InitNode;
PROCEDURE Index(s: ARRAY OF CHAR;cap: INTEGER): INTEGER;
VAR
i,sum: INTEGER;
BEGIN
sum := 0;
FOR i := 0 TO Strings.Length(s) DO
INC(sum,ORD(s[i]))
END;
RETURN sum MOD cap
END Index;
PROCEDURE ISort(VAR s: ARRAY OF CHAR);
VAR
i, j: INTEGER;
t: CHAR;
BEGIN
FOR i := 0 TO Strings.Length(s) - 1 DO
j := i;
t := s[j];
WHILE (j > 0) & (s[j -1] > t) DO
s[j] := s[j - 1];
DEC(j)
END;
s[j] := t
END
END ISort;
PROCEDURE SameLetters(x,y: ARRAY OF CHAR): BOOLEAN;
BEGIN
ISort(x);ISort(y);
RETURN (Strings.Compare(x,y) = 0)
END SameLetters;
PROCEDURE InitPool(p:Pool);
BEGIN
InitPoolWith(p,MAXPOOLSZ);
END InitPool;
PROCEDURE InitPoolWith(p:Pool;cap: INTEGER);
VAR
i: INTEGER;
BEGIN
p^.capacity := cap;
p^.max := 0;
NEW(p^.words,cap);
i := 0;
WHILE i < p^.capacity DO
p^.words^[i] := NIL;
INC(i);
END;
END InitPoolWith;
PROCEDURE (p: Pool) Add(w: ARRAY OF CHAR);
VAR
idx: INTEGER;
iter,n: Node;
BEGIN
idx := Index(w,p^.capacity);
iter := p^.words^[idx];
NEW(n);InitNode(n);COPY(w,n^.word);
WHILE(iter # NIL) DO
IF SameLetters(w,iter^.word) THEN
INC(iter^.count);
IF iter^.count > p^.max THEN p^.max := iter^.count END;
n^.desc := iter^.desc;
iter^.desc := n;
RETURN
END;
iter := iter^.next
END;
ASSERT(iter = NIL);
n^.next := p^.words^[idx];p^.words^[idx] := n
END Add;
PROCEDURE ShowAnagrams(l: Node);
VAR
iter: Node;
BEGIN
iter := l;
WHILE iter # NIL DO
Out.String(iter^.word);Out.String(" ");
iter := iter^.desc
END;
Out.Ln
END ShowAnagrams;
PROCEDURE (p: Pool) ShowMax();
VAR
i: INTEGER;
iter: Node;
BEGIN
FOR i := 0 TO LEN(p^.words^) - 1 DO
IF p^.words^[i] # NIL THEN
iter := p^.words^[i];
WHILE iter # NIL DO
IF iter^.count = p^.max THEN
ShowAnagrams(iter);
END;
iter := iter^.next
END
END
END
END ShowMax;
PROCEDURE DoProcess(fnm: ARRAY OF CHAR);
VAR
stdinBck,istream: Files.File;
line: String;
p: Pool;
BEGIN
istream := Files.Open(fnm,"r");
stdinBck := Files.stdin;
Files.stdin := istream;
NEW(p);InitPool(p);
WHILE In.Done DO
In.Line(line);
p.Add(line);
END;
Files.stdin := stdinBck;
Files.Close(istream);
p^.ShowMax();
END DoProcess;
BEGIN
DoProcess("unixdict.txt");
END Anagrams.

View file

@ -0,0 +1,29 @@
declare
%% Helper function
fun {ReadLines Filename}
File = {New class $ from Open.file Open.text end init(name:Filename)}
in
for collect:C break:B do
case {File getS($)} of false then {File close} {B}
[] Line then {C Line}
end
end
end
%% Groups anagrams by using a mutable dictionary
%% with sorted words as keys
WordDict = {Dictionary.new}
for Word in {ReadLines "unixdict.txt"} do
Keyword = {String.toAtom {Sort Word Value.'<'}}
in
WordDict.Keyword := Word|{CondSelect WordDict Keyword nil}
end
Sets = {Dictionary.items WordDict}
%% Filter such that only the largest sets remain
MaxSetSize = {FoldL {Map Sets Length} Max 0}
LargestSets = {Filter Sets fun {$ S} {Length S} == MaxSetSize end}
in
%% Display result (make sure strings are shown as string, not as number lists)
{Inspector.object configureEntry(widgetShowStrings true)}
{Inspect LargestSets}

View file

@ -0,0 +1,67 @@
/* Search a list of words, finding those having the same letters. */
word_test: proc options (main);
declare words (50000) character (20) varying,
frequency (50000) fixed binary;
declare word character (20) varying;
declare (i, k, wp, most) fixed binary (31);
on endfile (sysin) go to done;
words = ''; frequency = 0;
wp = 0;
do forever;
get edit (word) (L);
call search_word_list (word);
end;
done:
put skip list ('There are ' || wp || ' words');
most = 0;
/* Determine the word(s) having the greatest number of anagrams. */
do i = 1 to wp;
if most < frequency(i) then most = frequency(i);
end;
put skip edit ('The following word(s) have ', trim(most), ' anagrams:') (a);
put skip;
do i = 1 to wp;
if most = frequency(i) then put edit (words(i)) (x(1), a);
end;
search_word_list: procedure (word) options (reorder);
declare word character (*) varying;
declare i fixed binary (31);
do i = 1 to wp;
if length(words(i)) = length(word) then
if is_anagram(word, words(i)) then
do;
frequency(i) = frequency(i) + 1;
return;
end;
end;
/* The word does not exist in the list, so add it. */
if wp >= hbound(words,1) then return;
wp = wp + 1;
words(wp) = word;
frequency(wp) = 1;
return;
end search_word_list;
/* Returns true if the words are anagrams, otherwise returns false. */
is_anagram: procedure (word1, word2) returns (bit(1)) options (reorder);
declare (word1, word2) character (*) varying;
declare tword character (20) varying, c character (1);
declare (i, j) fixed binary;
tword = word2;
do i = 1 to length(word1);
c = substr(word1, i, 1);
j = index(tword, c);
if j = 0 then return ('0'b);
substr(tword, j, 1) = ' ';
end;
return ('1'b);
end is_anagram;
end word_test;

View file

@ -0,0 +1,88 @@
Program Anagrams;
// assumes a local file
uses
classes, math;
var
i, j, k, maxCount: integer;
sortedString: string;
WordList: TStringList;
SortedWordList: TStringList;
AnagramList: array of TStringlist;
begin
WordList := TStringList.Create;
WordList.LoadFromFile('unixdict.txt');
for i := 0 to WordList.Count - 1 do
begin
setLength(sortedString,Length(WordList.Strings[i]));
sortedString[1] := WordList.Strings[i][1];
// sorted assign
j := 2;
while j <= Length(WordList.Strings[i]) do
begin
k := j - 1;
while (WordList.Strings[i][j] < sortedString[k]) and (k > 0) do
begin
sortedString[k+1] := sortedString[k];
k := k - 1;
end;
sortedString[k+1] := WordList.Strings[i][j];
j := j + 1;
end;
// create the stringlists of the sorted letters and
// the list of the original words
if not assigned(SortedWordList) then
begin
SortedWordList := TStringList.Create;
SortedWordList.append(sortedString);
setlength(AnagramList,1);
AnagramList[0] := TStringList.Create;
AnagramList[0].append(WordList.Strings[i]);
end
else
begin
j := 0;
while sortedString <> SortedWordList.Strings[j] do
begin
inc(j);
if j = (SortedWordList.Count) then
begin
SortedWordList.append(sortedString);
setlength(AnagramList,length(AnagramList) + 1);
AnagramList[j] := TStringList.Create;
break;
end;
end;
AnagramList[j].append(WordList.Strings[i]);
end;
end;
maxCount := 1;
for i := 0 to length(AnagramList) - 1 do
maxCount := max(maxCount, AnagramList[i].Count);
// create output
writeln('The largest sets of words have ', maxCount, ' members:');
for i := 0 to length(AnagramList) - 1 do
begin
if AnagramList[i].Count = maxCount then
begin
write('"', SortedWordList.strings[i], '": ');
for j := 0 to AnagramList[i].Count - 2 do
write(AnagramList[i].strings[j], ', ');
writeln(AnagramList[i].strings[AnagramList[i].Count - 1]);
end;
end;
// Cleanup
WordList.Destroy;
SortedWordList.Destroy;
for i := 0 to length(AnagramList) - 1 do
AnagramList[i].Destroy;
end.

View file

@ -0,0 +1,5 @@
my %anagram = slurp('unixdict.txt').words.classify( { .comb.sort.join } );
my $max = [max] map { +@($_) }, %anagram.values;
%anagram.values.grep( { +@($_) >= $max } )».join(' ')».say;

View file

@ -0,0 +1,9 @@
slurp('unixdict.txt')\
.words\
.classify( *.comb.sort.join )\
.classify( +*.value )\
.sort( -*.key )[0]\
.value\
.values\
».value\
».say

View file

@ -0,0 +1,13 @@
$c = New-Object Net.WebClient
$words = -split ($c.DownloadString('http://www.puzzlers.org/pub/wordlists/unixdict.txt'))
$top_anagrams = $words `
| ForEach-Object {
$_ | Add-Member -PassThru NoteProperty Characters `
(-join (([char[]] $_) | Sort-Object))
} `
| Group-Object Characters `
| Group-Object Count `
| Sort-Object Count `
| Select-Object -First 1
$top_anagrams.Group | ForEach-Object { $_.Group -join ', ' }

View file

@ -0,0 +1,61 @@
InitNetwork() ;
OpenConsole()
Procedure.s sortWord(word$)
len.i = Len(word$)
Dim CharArray.s (len)
For n = 1 To len ; Transfering each single character
CharArray(n) = Mid(word$, n, 1) ; of the word into an array.
Next
SortArray(CharArray(),#PB_Sort_NoCase ) ; Sorting the array.
word$ =""
For n = 1 To len ; Writing back each single
word$ + CharArray(n) ; character of the array.
Next
ProcedureReturn word$
EndProcedure
tmpdir$ = GetTemporaryDirectory()
filename$ = tmpdir$ + "unixdict.txt"
Structure ana
isana.l
anas.s
EndStructure
NewMap anaMap.ana()
If ReceiveHTTPFile("http://www.puzzlers.org/pub/wordlists/unixdict.txt", filename$)
If ReadFile(1, filename$)
Repeat
word$ = (ReadString(1)) ; Reading a word from a file.
key$ = (sortWord(word$)) ; Sorting the word and storing in key$.
If FindMapElement(anaMap(), key$) ; Looking up if a word already had the same key$.
; if yes
anaMap()\anas = anaMap()\anas+ ", " + word$ ; adding the word
anaMap()\isana + 1
Else
; if no
anaMap(key$)\anas = word$ ; applying a new record
anaMap()\isana + 1
EndIf
Until Eof(1)
CloseFile(1)
DeleteFile(filename$)
;----- output -----
ForEach anaMap()
If anaMap()\isana >= 4 ; only emit what had 4 or more hits.
PrintN(anaMap()\anas)
EndIf
Next
PrintN("Press any key"): Repeat: Until Inkey() <> ""
EndIf
EndIf

View file

@ -0,0 +1,11 @@
import Prelude;
list[str] OrderedRep(str word){
return sort([word[i] | i <- [0..size(word)-1]]);
}
public list[set[str]] anagram(){
allwords = readFileLines(|http://www.puzzlers.org/pub/wordlists/unixdict.txt|);
AnagramMap = invert((word : OrderedRep(word) | word <- allwords));
longest = max([size(group) | group <- range(AnagramMap)]);
return [AnagramMap[rep]| rep <- AnagramMap, size(AnagramMap[rep]) == longest];
}

View file

@ -0,0 +1,8 @@
value: [
{"glean","galen","lange","angle","angel"},
{"glare","lager","regal","large","alger"},
{"carte","trace","crate","caret","cater"},
{"lane","lena","lean","elan","neal"},
{"able","bale","abel","bela","elba"},
{"levi","live","vile","evil","veil"}
]

View file

@ -0,0 +1,34 @@
on mouseUp
repeat for each word W in url "http://www.puzzlers.org/pub/wordlists/unixdict.txt"
put W & comma after A[sortChars(W)]
end repeat
put 0 into winningLength
repeat for each element E in A
get the number of items in E
if it < winningLength then next repeat
if it > winningLength then
put it into winningLength
put empty into winningList
end if
put (char 1 to -2 of E) & cr after winningList
end repeat
put winningList
end mouseUp
function sortChars X
get charsToItems(X)
sort items of it
return itemsToChars(it)
end sortChars
function charsToItems X
repeat for each char C in X
put C & comma after R
end repeat
return char 1 to -2 of R
end charsToItems
function itemsToChars X
replace comma with empty in X
return X
end itemsToChars

View file

@ -0,0 +1,67 @@
a$ = httpGet$("http://www.puzzlers.org/pub/wordlists/unixdict.txt") ' get the words from this web
sqliteconnect #mem, ":memory:" ' create in memory DB
#mem execute("CREATE TABLE words(theWord,sortWord)")
ii = 1
while ii
jj = instr(a$,chr$(10),ii + 1)
if jj > 0 then
theWord$ = mid$(a$,ii, jj - ii) ' get each word
if instr(theWord$,"'") <> 0 then theWord$ = dblQuote$(theWord$) ' eclipse the single quote
sortWord$ = theWord$
' ------------------------------------
' Sort word using the ol bubble sort
' ------------------------------------
j = 1
while j
j = 0
for i = 1 to len(sortWord$) - 1
if mid$(sortWord$,i,1) > mid$(sortWord$,i + 1,1) then
sortWord$ = left$(sortWord$,i - 1) + mid$(sortWord$,i + 1,1) + mid$(sortWord$,i,1) + mid$(sortWord$,i + 2)
j = 1
end if
next i
wend
' ----------------------------
' place in memory sql table
' ----------------------------
#mem execute("INSERT INTO words VALUES('";theWord$;"','";sortWord$;"')")
end if
ii = jj + 1
wend
' -----------------------------------------------------------
' Select matched words in word order and print in html table
' -----------------------------------------------------------
html "<table border=1>"
mem$ = "SELECT words.theWord,
matchWords.theWord as mWord
FROM words
JOIN words as matchWords
ON matchWords.sortWord = words.sortWord
AND matchWOrds.theWord <> words.theWord
ORDER BY words.theWord"
#mem execute(mem$)
WHILE #mem hasanswer()
#row = #mem #nextrow()
theWord$ = #row theWord$()
mWord$ = #row mWord$()
html "<tr><td>";theWord$;"</td><td>";mWord$;"</td></tr>"
WEND
html "</table>"
end
' -----------------------------------------
' Convert single quotes to double quotes
' -----------------------------------------
FUNCTION dblQuote$(str$)
i = 1
qq$ = ""
while (word$(str$,i,"'")) <> ""
dblQuote$ = dblQuote$;qq$;word$(str$,i,"'")
qq$ = "''"
i = i + 1
WEND
END FUNCTION

View file

@ -0,0 +1,40 @@
h := open('unixdict.txt', "r");
anagrams := {};
while not eof(h) loop
geta(h, word);
if word = om or word = "" then
continue;
end if;
sorted := insertion_sort(word);
anagrams{sorted} with:= word;
end loop;
max_size := 0;
max_words := {};
for words = anagrams{sorted} loop
size := #words;
if size > max_size then
max_size := size;
max_words := {words};
elseif size = max_size then
max_words with:= words;
end if;
end loop;
for w in max_words loop
print(w);
end loop;
-- GNU SETL has no built-in sort()
procedure insertion_sort(A);
for i in [2..#A] loop
v := A(i);
j := i-1;
while j >= 1 and A(j) > v loop
A(j+1) := A(j);
j := j - 1;
end loop;
A(j+1) := v;
end loop;
return A;
end procedure;

View file

@ -0,0 +1,23 @@
* # Sort letters of word
define('sortw(str)a,i,j') :(sortw_end)
sortw a = array(size(str))
sw1 i = i + 1; str len(1) . a<i> = :s(sw1)
a = sort(a)
sw2 j = j + 1; sortw = sortw a<j> :s(sw2)f(return)
sortw_end
* # Count words in string
define('countw(str)') :(countw_end)
countw str break(' ') span(' ') = :f(return)
countw = countw + 1 :(countw)
countw_end
ana = table()
L1 wrd = input :f(L2) ;* unixdict.txt from stdin
sw = sortw(wrd); ana<sw> = ana<sw> wrd ' '
cw = countw(ana<sw>); max = gt(cw,max) cw
i = i + 1; terminal = eq(remdr(i,1000),0) wrd :(L1)
L2 kv = convert(ana,'array')
L3 j = j + 1; key = kv<j,1>; val = kv<j,2> :f(end)
output = eq(countw(val),max) key ': ' val :(L3)
end

View file

@ -0,0 +1,28 @@
$$ MODE TUSCRIPT,{}
requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
DICT anagramm CREATE 99999
COMPILE
LOOP word=requestdata
-> ? : any character
charsInWord=STRINGS (word," ? ")
charString =ALPHA_SORT (charsInWord)
DICT anagramm APPEND/QUIET/COUNT charString,num,freq,word;" "
ENDLOOP
DICT anagramm UNLOAD charString,all,freq,anagrams
index =DIGIT_INDEX (freq)
reverseIndex =REVERSE (index)
freq =INDEX_SORT (freq,reverseIndex)
anagrams =INDEX_SORT (anagrams,reverseIndex)
charString =INDEX_SORT (charString,reverseIndex)
mostWords=SELECT (freq,1), adjust=MAX_LENGTH (charString)
LOOP cs=charString, f=freq, a=anagrams
IF (f<mostWords) EXIT
cs=CENTER (cs,-adjust)
PRINT cs," ",f,": ",a
ENDLOOP
ENDCOMPILE

View file

@ -0,0 +1,5 @@
#import std
#show+
anagrams = mat` * leql$^&h eql|=@rK2tFlSS ^(~&,-<&)* unixdict_dot_txt

View file

@ -0,0 +1,66 @@
File_Open("|(PATH_ONLY)\unixdict.txt")
Repeat(ALL) {
Reg_Copy_Block(10, CP, EOL_Pos) // original word
Call("SORT_LETTERS") // sort letters of the word
EOL
IC(' ') Reg_Ins(10) // add the original word at eol
Line(1, ERRBREAK)
}
Sort(0, File_Size) // sort list according to anagrams
BOF
Search("|F") Search(' ') // first word in the list
Reg_Copy_Block(10, BOL_Pos, CP+1) // reg 10 = sorted anagram word
Reg_Copy_Block(11, CP, EOL_Pos) // reg 11 = list of words in current group
Reg_Empty(12) // reg 12 = list of words in largest groups
Reg_Set(13, "
")
#1 = 1 // words in this group
#2 = 2 // words in largest group found
Repeat(ALL) {
Line(1, ERRBREAK)
if (Match(@10, ADVANCE) == 0) { // same group as previous word?
Reg_Copy_Block(11, CP-1, EOL_Pos, APPEND) // add word to this group
#1++
} else { // different anagram group
Search(" ", ERRBREAK)
if (#1 == #2) { // same size as the largest?
Reg_Set(12, @13, APPEND) // append newline
Reg_Set(12, @11, APPEND) // append word list
}
if (#1 > #2) { // new larger size of group
Reg_Set(12, @11) // replace word list
#2 = #1
}
Reg_Copy_Block(10, BOL_Pos, CP+1)
Reg_Copy_Block(11, CP, EOL_Pos) // first word of new group
#1 = 1
}
}
Buf_Quit(OK) // close word list file
Buf_Switch(Buf_Free) // output results in a new edit buffer
Reg_Ins(12) // display all groups of longest anagram words
Return
////////////////////////////////////////////////////////////////////
//
// Sort characters in current line using Insertion sort
//
:SORT_LETTERS:
GP(EOL_pos) #9 = Cur_Col-1
for (#1 = 2; #1 <= #9; #1++) {
Goto_Col(#1) #8 = Cur_Char
#2 = #1
while (#2 > 1) {
#7 = Cur_Char(-1)
if (#7 <= #8) { break }
Ins_Char(#7, OVERWRITE)
#2--
Goto_Col(#2)
}
Ins_Char(#8, OVERWRITE)
}
return

View file

@ -0,0 +1,64 @@
Imports System.IO
Imports System.Collections.ObjectModel
Module Module1
Dim sWords As New Dictionary(Of String, Collection(Of String))
Sub Main()
Dim oStream As StreamReader = Nothing
Dim sLines() As String = Nothing
Dim sSorted As String = Nothing
Dim iHighCount As Integer = 0
Dim iMaxKeyLength As Integer = 0
Dim sOutput As String = ""
oStream = New StreamReader("unixdict.txt")
sLines = oStream.ReadToEnd.Split(New String() {vbCrLf}, StringSplitOptions.RemoveEmptyEntries)
oStream.Close()
For i As Integer = 0 To sLines.GetUpperBound(0)
sSorted = SortCharacters(sLines(i))
If Not sWords.ContainsKey(sSorted) Then sWords.Add(sSorted, New Collection(Of String))
sWords(sSorted).Add(sLines(i))
If sWords(sSorted).Count > iHighCount Then
iHighCount = sWords(sSorted).Count
If sSorted.Length > iMaxKeyLength Then iMaxKeyLength = sSorted.Length
End If
Next
For Each sKey As String In sWords.Keys
If sWords(sKey).Count = iHighCount Then
sOutput &= "[" & sKey.ToUpper & "]" & Space(iMaxKeyLength - sKey.Length + 1) & String.Join(", ", sWords(sKey).ToArray()) & vbCrLf
End If
Next
Console.WriteLine(sOutput)
Console.ReadKey()
End Sub
Private Function SortCharacters(ByVal s As String) As String
Dim sReturn() As Char = s.ToCharArray()
Dim sTemp As Char = Nothing
For i As Integer = 0 To sReturn.GetUpperBound(0) - 1
If (sReturn(i + 1)) < (sReturn(i)) Then
sTemp = sReturn(i)
sReturn(i) = sReturn(i + 1)
sReturn(i + 1) = sTemp
i = -1
End If
Next
Return CStr(sReturn)
End Function
End Module