Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Ordered_words
note: text processing

View file

@ -0,0 +1,20 @@
An   ''ordered word''   is a word in which the letters appear in alphabetic order.
Examples include   '''abbey'''   and   '''dirt'''.
{{task heading}}
Find ''and display'' all the ordered words in the dictionary   [https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt]   that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
{{task heading|Related tasks}}
{{Related tasks/Word plays}}
{{Template:Strings}}
<br><br>

View file

@ -0,0 +1,5 @@
V words = File(unixdict.txt).read().split("\n")
V ordered = words.filter(word -> word == sorted(word))
V maxlen = max(ordered, key' w -> w.len).len
V maxorderedwords = ordered.filter(word -> word.len == :maxlen)
print(maxorderedwords.join( ))

View file

@ -0,0 +1,45 @@
PROC ordered = (STRING s)BOOL:
BEGIN
FOR i TO UPB s - 1 DO IF s[i] > s[i+1] THEN return false FI OD;
TRUE EXIT
return false: FALSE
END;
IF FILE input file;
STRING file name = "unixdict.txt";
open(input file, file name, stand in channel) /= 0
THEN
print(("Unable to open file """ + file name + """", newline))
ELSE
BOOL at eof := FALSE;
on logical file end (input file, (REF FILE f)BOOL: at eof := TRUE);
FLEX [1:0] STRING words;
INT idx := 1;
INT max length := 0;
WHILE NOT at eof
DO
STRING word;
get(input file, (word, newline));
IF UPB word >= max length
THEN IF ordered(word)
THEN
max length := UPB word;
IF idx > UPB words
THEN
[1 : UPB words + 20] STRING tmp;
tmp[1 : UPB words] := words;
words := tmp
FI;
words[idx] := word;
idx +:= 1
FI
FI
OD;
print(("Maximum length of ordered words: ", whole(max length, -4), newline));
FOR i TO idx-1
DO
IF UPB words[i] = max length THEN print((words[i], newline)) FI
OD
FI

View file

@ -0,0 +1,13 @@
resultlongest_ordered_words file_path
ffile_path ⎕NTIE 0 ⍝ open file
text⎕NREAD f 'char8' ⍝ read vector of 8bit chars
⎕NUNTIE f ⍝ close file
linestext~text(⎕UCS 10 13) ⍝ split into lines (\r\n)
⍝ filter only words with ordered characters
ordered_wordslines/{()}¨lines
⍝ find max of word lengths, filter only words with that length
resultordered_words/lengths=/lengths¨ordered_words

View file

@ -0,0 +1,36 @@
BEGIN {
abc = "abcdefghijklmnopqrstuvwxyz"
}
{
# Check if this line is an ordered word.
ordered = 1 # true
left = -1
for (i = 1; i <= length($0); i++) {
right = index(abc, substr($0, i, 1))
if (right == 0 || left > right) {
ordered = 0 # false
break
}
left = right
}
if (ordered) {
score = length($0)
if (score > best["score"]) {
# Reset the list of best ordered words.
best["score"] = score
best["count"] = 1
best[1] = $0
} else if (score == best["score"]) {
# Add this word to the list.
best[++best["count"]] = $0
}
}
}
END {
# Print the list of best ordered words.
for (i = 1; i <= best["count"]; i++)
print best[i]
}

View file

@ -0,0 +1,57 @@
CHAR ARRAY line(256)
BYTE FUNC IsOrderedWord(CHAR ARRAY word)
BYTE len,i
len=word(0)
IF len<=1 THEN RETURN (1) FI
FOR i=1 TO len-1
DO
IF word(i)>word(i+1) THEN
RETURN (0)
FI
OD
RETURN (1)
BYTE FUNC FindLongestOrdered(CHAR ARRAY fname)
BYTE max,dev=[1]
max=0
Close(dev)
Open(dev,fname,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
IF line(0)>max AND IsOrderedWord(line)=1 THEN
max=line(0)
FI
OD
Close(dev)
RETURN (max)
PROC FindWords(CHAR ARRAY fname BYTE n)
BYTE count,dev=[1]
Close(dev)
Open(dev,fname,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
IF line(0)=n AND IsOrderedWord(line)=1 THEN
Print(line) Put(32)
FI
OD
Close(dev)
RETURN
PROC Main()
CHAR ARRAY fname="H6:UNIXDICT.TXT"
BYTE max
PrintE("Finding the longest words...")
PutE()
max=FindLongestOrdered(fname)
FindWords(fname,max)
RETURN

View file

@ -0,0 +1,32 @@
with Ada.Text_IO, Ada.Containers.Indefinite_Vectors;
use Ada.Text_IO;
procedure Ordered_Words is
package Word_Vectors is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => String);
use Word_Vectors;
File : File_Type;
Ordered_Words : Vector;
Max_Length : Positive := 1;
begin
Open (File, In_File, "unixdict.txt");
while not End_Of_File (File) loop
declare
Word : String := Get_Line (File);
begin
if (for all i in Word'First..Word'Last-1 => Word (i) <= Word(i+1)) then
if Word'Length > Max_Length then
Max_Length := Word'Length;
Ordered_Words.Clear;
Ordered_Words.Append (Word);
elsif Word'Length = Max_Length then
Ordered_Words.Append (Word);
end if;
end if;
end;
end loop;
for Word of Ordered_Words loop
Put_Line (Word);
end loop;
Close (File);
end Ordered_Words;

View file

@ -0,0 +1,39 @@
integer
ordered(data s)
{
integer a, c, p;
a = 1;
p = -1;
for (, c in s) {
if (c < p) {
a = 0;
break;
} else {
p = c;
}
}
a;
}
integer
main(void)
{
file f;
text s;
index x;
f.affix("unixdict.txt");
while (f.line(s) != -1) {
if (ordered(s)) {
x.v_list(~s).append(s);
}
}
l_ucall(x.back, o_, 0, "\n");
return 0;
}

View file

@ -0,0 +1,43 @@
use AppleScript version "2.3.1" -- Mac OS 10.9 (Mavericks) or later — for these 'use' commands.
use sorter : script "Insertion sort" -- https://www.rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#AppleScript.
use scripting additions
on longestOrderedWords(wordList)
script o
property allWords : wordList
property orderedWords : {}
end script
set longestWordLength to 0
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
ignoring case
repeat with i from 1 to (count o's allWords)
set thisWord to item i of o's allWords
set thisWordLength to (count thisWord)
if (thisWordLength longestWordLength) then
set theseCharacters to thisWord's characters
tell sorter to sort(theseCharacters, 1, -1)
set sortedWord to theseCharacters as text
if (sortedWord = thisWord) then
if (thisWordLength > longestWordLength) then
set o's orderedWords to {thisWord}
set longestWordLength to thisWordLength
else
set end of o's orderedWords to thisWord
end if
end if
end if
end repeat
end ignoring
set AppleScript's text item delimiters to astid
return (o's orderedWords)
end longestOrderedWords
-- Test code:
local wordList
set wordList to paragraphs of (read (((path to desktop as text) & "www.rosettacode.org:unixdict.txt") as alias) as «class utf8»)
-- ignoring white space, punctuation and diacriticals
return longestOrderedWords(wordList)
--- end ignoring

View file

@ -0,0 +1 @@
{"abbott", "accent", "accept", "access", "accost", "almost", "bellow", "billow", "biopsy", "chilly", "choosy", "choppy", "effort", "floppy", "glossy", "knotty"}

View file

@ -0,0 +1,14 @@
ordered?: function [w]->
w = join sort split w
words: read.lines relative "unixdict.txt"
ret: new []
loop words 'wrd [
if ordered? wrd ->
'ret ++ #[w: wrd l: size wrd]
]
sort.descending.by: 'l 'ret
maxl: get first ret 'l
print sort map select ret 'x -> maxl = x\l
'x -> x\w

View file

@ -0,0 +1,33 @@
MaxLen=0
Loop, Read, UnixDict.txt ; Assigns A_LoopReadLine to each line of the file
{
thisword := A_LoopReadLine ; Just for readability
blSort := isSorted(thisWord) ; reduce calls to IsSorted to improve performance
ThisLen := StrLen(ThisWord) ; reduce calls to StrLen to improve performance
If (blSort = true and ThisLen = maxlen)
list .= ", " . thisword
Else If (blSort = true and ThisLen > maxlen)
{
list := thisword
maxlen := ThisLen
}
}
IsSorted(word){ ; This function uses the ASCII value of the letter to determine its place in the alphabet.
; Thankfully, the dictionary is in all lowercase
lastchar=0
Loop, parse, word
{
if ( Asc(A_LoopField) < lastchar )
return false
lastchar := Asc(A_loopField)
}
return true
}
GUI, Add, Edit, w300 ReadOnly, %list%
GUI, Show
return ; End Auto-Execute Section
GUIClose:
ExitApp

View file

@ -0,0 +1,19 @@
dict% = OPENIN("unixdict.txt")
IF dict%=0 ERROR 100, "Failed to open dictionary file"
max% = 2
REPEAT
A$ = GET$#dict%
IF LENA$ >= max% THEN
i% = 0
REPEAT i% += 1
UNTIL ASCMID$(A$,i%) > ASCMID$(A$,i%+1)
IF i% = LENA$ THEN
IF i% > max% max% = i% : list$ = ""
list$ += A$ + CHR$13 + CHR$10
ENDIF
ENDIF
UNTIL EOF#dict%
CLOSE #dict%
PRINT list$
END

View file

@ -0,0 +1,3 @@
words•FLines "unixdict.txt"
¯1(¨)()¨/words
"abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow" "biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty"

View file

@ -0,0 +1,20 @@
'Ordered words - improved version
OPTION COLLAPSE TRUE
list$ = LOAD$("unixdict.txt")
FOR word$ IN list$ STEP NL$
term$ = EXTRACT$(SORT$(EXPLODE$(word$, 1)), " ")
IF word$ = term$ THEN
IF LEN(term$) > MaxLen THEN
MaxLen = LEN(term$)
result$ = word$
ELIF LEN(term$) = MaxLen THEN
result$ = APPEND$(result$, 0, word$, NL$)
END IF
END IF
NEXT
PRINT result$

View file

@ -0,0 +1,3 @@
00p30p>_010p120p0>#v0~>>\$::48*\`\"~"`+!>>#v_$:#v_>30g:!#v_1-30p55+0>:30g3+g\1v
>0#v _$^#::\p04:<^+>#1^#\p01:p02*g02!`\g01:<@$ _ ,#!>#:<$<^<!:g03$<_^#!`\g00:+<
^<o>\30g2+p40g1+^0p00p03+1*g03!-g00 < < < < < <:>#$:#$00g#<\#<`#<!#<2#$0g#<*#<_

View file

@ -0,0 +1,25 @@
( orderedWords
= bow result longestLength word character
. 0:?bow
& :?result
& 0:?longestLength
& @( get$(!arg,STR)
: ?
( [!bow %?word \n [?bow ?
& @( !word
: ( ? %@?character <%@!character ?
| ?
( [!longestLength
& !word !result:?result
| [>!longestLength:[?longestLength
& !word:?result
|
)
)
)
& ~`
)
)
| !result
)
& orderedWords$"unixdict.txt"

View file

@ -0,0 +1 @@
ln{so}f[^^{L[}>mL[bx(==)[+(L[)+]f[uN

View file

@ -0,0 +1,38 @@
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
bool ordered(const std::string &word)
{
return std::is_sorted(word.begin(), word.end()); // C++11
}
int main()
{
std::ifstream infile("unixdict.txt");
if (!infile) {
std::cerr << "Can't open word file\n";
return -1;
}
std::vector<std::string> words;
std::string word;
int longest = 0;
while (std::getline(infile, word)) {
int length = word.length();
if (length < longest) continue; // don't test short words
if (ordered(word)) {
if (longest < length) {
longest = length; // set new minimum length
words.clear(); // reset the container
}
words.push_back(word);
}
}
std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}

View file

@ -0,0 +1,30 @@
using System;
using System.Linq;
using System.Net;
static class Program
{
static void Main(string[] args)
{
WebClient client = new WebClient();
string text = client.DownloadString("http://www.puzzlers.org/pub/wordlists/unixdict.txt");
string[] words = text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var query = from w in words
where IsOrderedWord(w)
group w by w.Length into ows
orderby ows.Key descending
select ows;
Console.WriteLine(string.Join(", ", query.First().ToArray()));
}
private static bool IsOrderedWord(string w)
{
for (int i = 1; i < w.Length; i++)
if (w[i] < w[i - 1])
return false;
return true;
}
}

View file

@ -0,0 +1,83 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#define MAXLEN 100
typedef char TWord[MAXLEN];
typedef struct Node {
TWord word;
struct Node *next;
} Node;
int is_ordered_word(const TWord word) {
assert(word != NULL);
int i;
for (i = 0; word[i] != '\0'; i++)
if (word[i] > word[i + 1] && word[i + 1] != '\0')
return 0;
return 1;
}
Node* list_prepend(Node* words_list, const TWord new_word) {
assert(new_word != NULL);
Node *new_node = malloc(sizeof(Node));
if (new_node == NULL)
exit(EXIT_FAILURE);
strcpy(new_node->word, new_word);
new_node->next = words_list;
return new_node;
}
Node* list_destroy(Node *words_list) {
while (words_list != NULL) {
Node *temp = words_list;
words_list = words_list->next;
free(temp);
}
return words_list;
}
void list_print(Node *words_list) {
while (words_list != NULL) {
printf("\n%s", words_list->word);
words_list = words_list->next;
}
}
int main() {
FILE *fp = fopen("unixdict.txt", "r");
if (fp == NULL)
return EXIT_FAILURE;
Node *words = NULL;
TWord line;
unsigned int max_len = 0;
while (fscanf(fp, "%99s\n", line) != EOF) {
if (strlen(line) > max_len && is_ordered_word(line)) {
max_len = strlen(line);
words = list_destroy(words);
words = list_prepend(words, line);
} else if (strlen(line) == max_len && is_ordered_word(line)) {
words = list_prepend(words, line);
}
}
fclose(fp);
list_print(words);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,87 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#define MAXLEN 100
typedef char TWord[MAXLEN];
typedef struct WordsArray {
TWord *words;
size_t len;
} WordsArray;
int is_ordered_word(const TWord word) {
assert(word != NULL);
int i;
for (i = 0; word[i] != '\0'; i++)
if (word[i] > word[i + 1] && word[i + 1] != '\0')
return 0;
return 1;
}
void array_append(WordsArray *words_array, const TWord new_word) {
assert(words_array != NULL);
assert(new_word != NULL);
assert((words_array->len == 0) == (words_array->words == NULL));
words_array->len++;
words_array->words = realloc(words_array->words,
words_array->len * sizeof(words_array->words[0]));
if (words_array->words == NULL)
exit(EXIT_FAILURE);
strcpy(words_array->words[words_array->len-1], new_word);
}
void array_free(WordsArray *words_array) {
assert(words_array != NULL);
free(words_array->words);
words_array->words = NULL;
words_array->len = 0;
}
void list_print(WordsArray *words_array) {
assert(words_array != NULL);
size_t i;
for (i = 0; i < words_array->len; i++)
printf("\n%s", words_array->words[i]);
}
int main() {
FILE *fp = fopen("unixdict.txt", "r");
if (fp == NULL)
return EXIT_FAILURE;
WordsArray words;
words.len = 0;
words.words = NULL;
TWord line;
line[0] = '\0';
unsigned int max_len = 0;
while (fscanf(fp, "%99s\n", line) != EOF) { // 99 = MAXLEN - 1
if (strlen(line) > max_len && is_ordered_word(line)) {
max_len = strlen(line);
array_free(&words);
array_append(&words, line);
} else if (strlen(line) == max_len && is_ordered_word(line)) {
array_append(&words, line);
}
}
fclose(fp);
list_print(&words);
array_free(&words);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,54 @@
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
#include <string.h>
int ordered(char *s, char **end)
{
int r = 1;
while (*++s != '\n' && *s != '\r' && *s != '\0')
if (s[0] < s[-1]) r = 0;
*end = s;
return r;
}
int main()
{
char *buf, *word, *end, *tail;
struct stat st;
int longest = 0, len, fd;
if ((fd = open("unixdict.txt", O_RDONLY)) == -1) err(1, "read error");
fstat(fd, &st);
if (!(buf = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)))
err(1, "mmap");
for (word = end = buf; end < buf + st.st_size; word = end) {
while (*word == '\r' || *word == '\n') word++;
if (!ordered(word, &end)) continue;
if ((len = end - word + 1) < longest) continue;
if (len > longest) {
tail = buf; /* longer words found; reset out buffer */
longest = len;
}
/* use the same mmap'd region to store output. because of MAP_PRIVATE,
* change will not go back to file. mmap is copy on write, and we are using
* only the head space to store output, so kernel doesn't need to copy more
* than the words we saved--in this case, one page tops.
*/
memcpy(tail, word, len);
tail += len;
*tail = '\0';
}
printf(buf);
munmap(buf, st.st_size);
close(fd);
return 0;
}

View file

@ -0,0 +1,43 @@
is_ordered = proc (s: string) returns (bool)
last: char := '\000'
for c: char in string$chars(s) do
if last > c then return(false) end
last := c
end
return(true)
end is_ordered
lines = iter (s: stream) yields (string)
while true do
yield(stream$getl(s))
except when end_of_file: break end
end
end lines
ordered_words = proc (s: stream) returns (array[string])
words: array[string]
max_len: int := 0
for word: string in lines(s) do
if is_ordered(word) then
len: int := string$size(word)
if len > max_len then
max_len := len
words := array[string]$[]
elseif len = max_len then
array[string]$addh(words,word)
end
end
end
return(words)
end ordered_words
start_up = proc ()
dict: stream := stream$open(file_name$parse("unixdict.txt"), "read")
words: array[string] := ordered_words(dict)
stream$close(dict)
po: stream := stream$primary_output()
for word: string in array[string]$elements(words) do
stream$putl(po, word)
end
end start_up

View file

@ -0,0 +1,66 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. ABC-WORDS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DICT ASSIGN TO DISK
ORGANIZATION LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DICT
LABEL RECORD STANDARD
VALUE OF FILE-ID IS "unixdict.txt".
01 ENTRY.
03 WORD PIC X(32).
03 LETTERS PIC X OCCURS 32 TIMES, REDEFINES WORD.
WORKING-STORAGE SECTION.
01 LEN PIC 99.
01 MAXLEN PIC 99 VALUE 0.
01 I PIC 99.
01 OK-FLAG PIC X.
88 OK VALUE '*'.
PROCEDURE DIVISION.
BEGIN.
OPEN INPUT DICT.
FIND-LONGEST-WORD.
READ DICT, AT END CLOSE DICT, GO TO PRINT-LONGEST-WORDS.
PERFORM CHECK-WORD.
GO TO FIND-LONGEST-WORD.
PRINT-LONGEST-WORDS.
ALTER VALID-WORD TO PROCEED TO SHOW-WORD.
OPEN INPUT DICT.
READ-WORDS.
READ DICT, AT END CLOSE DICT, STOP RUN.
PERFORM CHECK-WORD.
GO TO READ-WORDS.
CHECK-WORD.
MOVE ZERO TO LEN.
INSPECT WORD TALLYING LEN
FOR CHARACTERS BEFORE INITIAL SPACE.
MOVE '*' TO OK-FLAG.
PERFORM CHECK-CHAR-PAIR VARYING I FROM 2 BY 1
UNTIL NOT OK OR I IS GREATER THAN LEN.
IF OK, PERFORM DO-WORD.
CHECK-CHAR-PAIR.
IF LETTERS(I - 1) IS GREATER THAN LETTERS(I),
MOVE SPACE TO OK-FLAG.
DO-WORD SECTION.
VALID-WORD.
GO TO CHECK-LENGTH.
CHECK-LENGTH.
IF LEN IS GREATER THAN MAXLEN, MOVE LEN TO MAXLEN.
GO TO DONE.
SHOW-WORD.
IF LEN IS EQUAL TO MAXLEN, DISPLAY WORD.
DONE.
EXIT.

View file

@ -0,0 +1,15 @@
(defn is-sorted? [coll]
(not-any? pos? (map compare coll (next coll))))
(defn take-while-eqcount [coll]
(let [n (count (first coll))]
(take-while #(== n (count %)) coll)))
(with-open [rdr (clojure.java.io/reader "unixdict.txt")]
(->> rdr
line-seq
(filter is-sorted?)
(sort-by count >)
take-while-eqcount
(clojure.string/join ", ")
println))

View file

@ -0,0 +1 @@
abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty

View file

@ -0,0 +1,21 @@
ordered_word = (word) ->
for i in [0...word.length - 1]
return false unless word[i] <= word[i+1]
true
show_longest_ordered_words = (candidates, dict_file_name) ->
words = ['']
for word in candidates
continue if word.length < words[0].length
if ordered_word word
words = [] if word.length > words[0].length
words.push word
return if words[0] == '' # we came up empty
console.log "Longest Ordered Words (source=#{dict_file_name}):"
for word in words
console.log word
dict_file_name = 'unixdict.txt'
file_content = require('fs').readFileSync dict_file_name
dict_words = file_content.toString().split '\n'
show_longest_ordered_words dict_words, dict_file_name

View file

@ -0,0 +1,18 @@
> coffee ordered_words.coffee
Longest Ordered Words (source=unixdict.txt):
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty

View file

@ -0,0 +1,26 @@
(defun orderedp (word)
(reduce (lambda (prev curr)
(when (char> prev curr) (return-from orderedp nil))
curr)
word)
t)
(defun longest-ordered-words (filename)
(let ((result nil))
(with-open-file (s filename)
(loop
with greatest-length = 0
for word = (read-line s nil)
until (null word)
do (let ((length (length word)))
(when (and (>= length greatest-length)
(orderedp word))
(when (> length greatest-length)
(setf greatest-length length
result nil))
(push word result)))))
(nreverse result)))
CL-USER> (longest-ordered-words "unixdict.txt")
("abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow"
"biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty")

View file

@ -0,0 +1,83 @@
include "cowgol.coh";
include "strings.coh";
include "file.coh";
var filename: [uint8] := "unixdict.txt";
# Call a subroutine for every line in a file
interface LineCb(line: [uint8]);
sub ForEachLine(fcb: [FCB], fn: LineCb) is
var linebuf: uint8[256];
var bufptr := &linebuf[0];
var len := FCBExt(fcb); # get length of file
FCBSeek(fcb, 0); # start at beginning of file
while len > 0 loop
var ch := FCBGetChar(fcb);
if ch == '\n' then
# end of line, terminate string
[bufptr] := 0;
fn(&linebuf[0]);
bufptr := &linebuf[0];
else
# add char to buffer
[bufptr] := ch;
bufptr := @next bufptr;
end if;
len := len - 1;
end loop;
# If the file doesn't cleanly end on a line terminator,
# also call for last incomplete line
if ch != '\n' then
[bufptr] := 0;
fn(&linebuf[0]);
end if;
end sub;
# Check if the letters in a word appear in alphabetical order
sub isOrdered(word: [uint8]): (r: uint8) is
var cr := [word];
word := @next word;
loop
var cl := cr;
cr := [word];
word := @next word;
if cr < 32 then
r := 1;
return;
elseif (cl | 32) > (cr | 32) then
r := 0;
return;
end if;
end loop;
end sub;
# Find maximum length of ordered words
var maxLen: uint8 := 0;
sub MaxOrderedLength implements LineCb is
var len := StrLen(line) as uint8;
if maxLen < len and isOrdered(line) != 0 then
maxLen := len;
end if;
end sub;
# Print all ordered words matching maximum length
sub PrintMaxLenWord implements LineCb is
if maxLen == StrLen(line) as uint8 and isOrdered(line) != 0 then
print(line);
print_nl();
end if;
end sub;
var fcb: FCB;
if FCBOpenIn(&fcb, filename) != 0 then
print("cannot open unixdict.txt\n");
ExitWithError();
end if;
ForEachLine(&fcb, MaxOrderedLength);
ForEachLine(&fcb, PrintMaxLenWord);
var foo := FCBClose(&fcb);

View file

@ -0,0 +1,20 @@
void main() {
import std.stdio, std.algorithm, std.range, std.string;
string[] result;
size_t maxLen;
foreach (string word; "unixdict.txt".File.lines) {
word = word.chomp;
immutable len = word.walkLength;
if (len < maxLen || !word.isSorted)
continue;
if (len > maxLen) {
result = [word];
maxLen = len;
} else
result ~= word;
}
writefln("%-(%s\n%)", result);
}

View file

@ -0,0 +1,19 @@
void main() {
import std.stdio, std.algorithm, std.file, std.range;
string[] result;
size_t maxWalkLen;
foreach (word; "unixdict.txt".readText.splitter) {
if (word.length >= maxWalkLen && word.isSorted) {
immutable wlen = word.walkLength;
if (wlen > maxWalkLen) {
result.length = 0;
maxWalkLen = wlen;
}
result ~= word.idup;
}
}
writefln("%-(%s\n%)", result);
}

View file

@ -0,0 +1,7 @@
void main() {
import std.stdio, std.algorithm, std.range, std.file, std.string;
auto words = "unixdict.txt".readText.split.filter!isSorted;
immutable maxLen = words.map!q{a.length}.reduce!max;
writefln("%-(%s\n%)", words.filter!(w => w.length == maxLen));
}

View file

@ -0,0 +1,41 @@
import std.stdio, core.stdc.string, std.mmfile, std.algorithm;
const(char)[] findWord(const char[] s) pure nothrow @safe @nogc {
size_t wordEnd = 0;
while (wordEnd < s.length && s[wordEnd] != '\n' && s[wordEnd] != '\r')
wordEnd++;
return s[0 .. wordEnd];
}
void main() {
auto mmf = new MmFile("unixdict.txt", MmFile.Mode.readCopyOnWrite, 0, null);
auto txt = cast(char[])(mmf[]);
size_t maxLen = 0, outStart = 0;
for (size_t wordStart = 0; wordStart < txt.length; ) {
while (wordStart < txt.length &&
(txt[wordStart] == '\r' || txt[wordStart] == '\n'))
wordStart++;
const word = findWord(txt[wordStart .. $]);
wordStart += word.length;
if (word.length < maxLen || !word.isSorted)
continue;
if (word.length > maxLen) {
// Longer ordered word found, reset the out buffer.
outStart = 0;
maxLen = word.length;
}
// Use the same mmap'd region to store output. Because of
// Mode.readCopyOnWrite, change will not go back to file.
// We are using only the head space to store output, so
// kernel doesn't need to copy more than the words we saved,
// in this case, one page tops.
memcpy(&txt[outStart], word.ptr, word.length);
outStart += word.length;
txt[outStart++] = '\n'; // Words separator in out buffer.
}
txt[0 .. outStart].write;
}

View file

@ -0,0 +1,54 @@
program POrderedWords;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes, IdHTTP;
function IsOrdered(const s:string): Boolean;
var
I: Integer;
begin
Result := Length(s)<2; // empty or 1 char strings are ordered
for I := 2 to Length(s) do
if s[I]<s[I-1] then // can improve using case/localization to order...
Exit;
Result := True;
end;
function ProcessDictionary(const AUrl: string): string;
var
slInput: TStringList;
I, WordSize: Integer;
begin
slInput := TStringList.Create;
try
with TIdHTTP.Create(nil) do try
slInput.Text := Get(AUrl);
finally
Free;
end;
// or use slInput.LoadFromFile('yourfilename') to load from a local file
WordSize :=0;
for I := 0 to slInput.Count-1 do begin
if IsOrdered(slInput[I]) then
if (Length(slInput[I]) = WordSize) then
Result := Result + slInput[I] + ' '
else if (Length(slInput[I]) > WordSize) then begin
Result := slInput[I] + ' ';
WordSize := Length(slInput[I]);
end;
end;
finally
slInput.Free;
end;
end;
begin
try
WriteLn(ProcessDictionary('http://www.puzzlers.org/pub/wordlists/unixdict.txt'));
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.

View file

@ -0,0 +1 @@
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty

View file

@ -0,0 +1,36 @@
\util.g
proc nonrec is_ordered(*char str) bool:
while str* /= '\e' and str* <= (str+1)* do
str := str + 1
od;
str* = '\e' or (str+1)* = '\e'
corp
proc nonrec main() void:
[64]char buf;
*char str;
word length, max_length;
file(1024) dictfile;
channel input text dict;
str := &buf[0];
max_length := 0;
open(dict, dictfile, "unixdict.txt");
while readln(dict; str) do
if is_ordered(str) then
length := CharsLen(str);
if length > max_length then max_length := length fi
fi
od;
close(dict);
open(dict, dictfile, "unixdict.txt");
while readln(dict; str) do
if is_ordered(str) then
length := CharsLen(str);
if length = max_length then writeln(str) fi
fi
od;
close(dict)
corp

View file

@ -0,0 +1,7 @@
pragma.enable("accumulator")
def words := <http://www.puzzlers.org/pub/wordlists/unixdict.txt>.getText().split("\n")
def ordered := accum [] for word ? (word.sort() <=> word) in words { _.with(word) }
def maxLen := accum 0 for word in ordered { _.max(word.size()) }
def maxOrderedWords := accum [] for word ? (word.size() <=> maxLen) in ordered { _.with(word) }
println(" ".rjoin(maxOrderedWords))

View file

@ -0,0 +1,11 @@
def best := [].diverge()
for `@word$\n` ? (word.sort() <=> word) in <http://www.puzzlers.org/pub/wordlists/unixdict.txt> {
if (best.size() == 0) {
best.push(word)
} else if (word.size() > best[0].size()) {
best(0) := [word] # replace all
} else if (word.size() <=> best[0].size()) {
best.push(word)
}
}
println(" ".rjoin(best.snapshot()))

View file

@ -0,0 +1,26 @@
(define (ordered? str)
(for/and ([i (in-range 1 (string-length str))])
(string-ci<=? (string-ref str (1- i)) (string-ref str i))))
(define (ordre words)
(define wl 0)
(define s 's)
(for/fold (len 0) ((w words))
(set! wl (string-length w))
#:continue (< wl len)
#:when (ordered? w)
#:continue (and (= len wl) (push s w))
(push (stack s) w) ;; start a new list of length wl
wl)
(stack->list s))
;; output
(load 'unixdict)
(ordre (text-parse unixdict))
→ (abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty)
;; with the dictionaries provided with EchoLisp
;; french
→ (accentué) ;; ordered, longest, and ... self-reference
;; english
→ (Adelops alloquy beefily begorry billowy egilops)

View file

@ -0,0 +1,8 @@
File.read!("unixdict.txt")
|> String.split
|> Enum.filter(fn word -> String.codepoints(word) |> Enum.sort |> Enum.join == word end)
|> Enum.group_by(fn word -> String.length(word) end)
|> Enum.max_by(fn {length,_words} -> length end)
|> elem(1)
|> Enum.sort
|> Enum.each(fn word -> IO.puts word end)

View file

@ -0,0 +1,21 @@
-module( ordered_words ).
-export( [is_ordered/1, task/0] ).
is_ordered( Word ) -> lists:sort( Word ) =:= Word.
task() ->
ok = find_unimplemented_tasks:init_http(),
Ordered_words = [X || X <- words(), is_ordered(X)],
Sorted_longest_length_first = lists:reverse( sort_with_length( Ordered_words ) ),
[{Max_length, _Word1} | _T] = Sorted_longest_length_first,
Longest_length_first = lists:takewhile( fun({Length, _Word2}) -> Length =:= Max_length end, Sorted_longest_length_first ),
[X || {_Length, X} <- Longest_length_first].
sort_with_length( Words ) ->
Words_with_length_first = [{erlang:length(X), X} || X <- Words],
lists:sort( Words_with_length_first ).
words() -> anagrams_deranged:words_from_url( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ).

View file

@ -0,0 +1,36 @@
include misc.e
type ordered(sequence s)
for i = 1 to length(s)-1 do
-- assume all items in the sequence are atoms
if s[i]>s[i+1] then
return 0
end if
end for
return 1
end type
integer maxlen
sequence words
object word
constant fn = open("unixdict.txt","r")
maxlen = -1
while 1 do
word = gets(fn)
if atom(word) then
exit
end if
word = word[1..$-1] -- truncate new-line
if length(word) >= maxlen and ordered(word) then
if length(word) > maxlen then
maxlen = length(word)
words = {}
end if
words = append(words,word)
end if
end while
close(fn)
pretty_print(1,words,{2})

View file

@ -0,0 +1,13 @@
open System
open System.IO
let longestOrderedWords() =
let isOrdered = Seq.pairwise >> Seq.forall (fun (a,b) -> a <= b)
File.ReadLines("unixdict.txt")
|> Seq.filter isOrdered
|> Seq.groupBy (fun s -> s.Length)
|> Seq.sortBy (fst >> (~-))
|> Seq.head |> snd
longestOrderedWords() |> Seq.iter (printfn "%s")

View file

@ -0,0 +1,33 @@
#APPTYPE CONSOLE
FUNCTION RESTfulGET(url)
DIM %HTTP = CREATEOBJECT("WinHttp.WinHttpRequest.5.1")
CALLMETHOD(HTTP, ".open %s, %s, %d", "GET", url, FALSE)
CALLMETHOD(HTTP, ".send")
RETURN GETVALUE("%s", HTTP, ".ResponseText")
END FUNCTION
DIM $TEXT = RESTfulGET("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
DIM dict[] = Split(TEXT, CHR(10))
DIM max AS INTEGER = UBOUND(dict)
DIM theword AS STRING
DIM words[]
FOR DIM i = 0 TO max
theWord = dict[i]
IF isOrdered(theWord) THEN
words[LEN(theWord)] = words[LEN(theWord)] & " " & theWord
END IF
NEXT
PRINT words[UBOUND(words)]
PAUSE
FUNCTION isOrdered(s)
FOR DIM i = 1 TO LEN(s) - 1
IF s{i} > s{i + 1} THEN
RETURN FALSE
END IF
NEXT
RETURN TRUE
END FUNCTION

View file

@ -0,0 +1,17 @@
USING: grouping http.client io io.encodings.utf8 io.files
io.files.temp kernel math memoize sequences sequences.extras
unicode.case urls ;
IN: rosetta-code.ordered-words
MEMO: word-list ( -- seq )
"unixdict.txt" temp-file dup exists? [
URL" http://puzzlers.org/pub/wordlists/unixdict.txt"
over download-to
] unless utf8 file-lines ;
: ordered-word? ( word -- ? )
>lower [ <= ] monotonic? ;
: ordered-words-main ( -- )
word-list [ ordered-word? ] filter
all-longest [ print ] each ;

View file

@ -0,0 +1,30 @@
class Main
{
public static Bool ordered (Str word)
{
word.chars.all |Int c, Int i -> Bool|
{
(i == (word.size-1) || c <= word.chars[i+1])
}
}
public static Void main ()
{
Str[] words := [,]
File(`unixdict.txt`).eachLine |Str word|
{
if (ordered(word))
{
if (words.isEmpty || words.first.size < word.size)
{ // reset the list
words = [word]
}
else if (words.size >= 1 && words.first.size == word.size)
{ // add word to existing ones
words.add (word)
}
}
}
echo (words.join (" "))
}
}

View file

@ -0,0 +1,44 @@
include lib/stmstack.4th \ include string stack library
: check-word ( a n -- a n f)
2dup bl >r \ start off with a space
begin
dup \ when not end of word
while
over c@ r@ >= \ check character
while
r> drop over c@ >r chop \ chop character off
repeat r> drop nip 0= \ cleanup and set flag
;
: open-file ( -- h)
1 dup argn = abort" Usage: ordered infile"
args input open error? abort" Cannot open file"
dup use \ return and use the handle
;
: read-file ( --)
0 >r \ begin with zero length
begin
refill \ EOF detected?
while
0 parse dup r@ >= \ equal or longer string length?
if \ check the word and adjust length
check-word if r> drop dup >r >s else 2drop then
else \ if it checks out, put on the stack
2drop \ otherwise drop the word
then
repeat r> drop \ clean it up
;
: read-back ( --)
s> dup >r type cr \ longest string is on top of stack
begin s> dup r@ >= while type cr repeat
2drop r> drop \ keep printing until shorter word
; \ has been found
: ordered ( --)
open-file s.clear read-file read-back close
; \ open file, clear the stack, read file
\ read it back and close the file
ordered

View file

@ -0,0 +1,113 @@
!***************************************************************************************
module ordered_module
!***************************************************************************************
implicit none
!the dictionary file:
integer,parameter :: file_unit = 1000
character(len=*),parameter :: filename = 'unixdict.txt'
!maximum number of characters in a word:
integer,parameter :: max_chars = 50
type word
character(len=max_chars) :: str !the word from the dictionary
integer :: n = 0 !length of this word
logical :: ordered = .false. !if it is an ordered word
end type word
!the dictionary structure:
type(word),dimension(:),allocatable :: dict
contains
!***************************************************************************************
!******************************************************************************
function count_lines_in_file(fid) result(n_lines)
!******************************************************************************
implicit none
integer :: n_lines
integer,intent(in) :: fid
character(len=1) :: tmp
integer :: i
integer :: ios
!the file is assumed to be open already.
rewind(fid) !rewind to beginning of the file
n_lines = 0
do !read each line until the end of the file.
read(fid,'(A1)',iostat=ios) tmp
if (ios < 0) exit !End of file
n_lines = n_lines + 1 !row counter
end do
rewind(fid) !rewind to beginning of the file
!******************************************************************************
end function count_lines_in_file
!******************************************************************************
!******************************************************************************
pure elemental function ordered_word(word) result(yn)
!******************************************************************************
! turns true if word is an ordered word, false if it is not.
!******************************************************************************
implicit none
character(len=*),intent(in) :: word
logical :: yn
integer :: i
yn = .true.
do i=1,len_trim(word)-1
if (ichar(word(i+1:i+1))<ichar(word(i:i))) then
yn = .false.
exit
end if
end do
!******************************************************************************
end function ordered_word
!******************************************************************************
!***************************************************************************************
end module ordered_module
!***************************************************************************************
!****************************************************
program main
!****************************************************
use ordered_module
implicit none
integer :: i,n,n_max
!open the dictionary and read in all the words:
open(unit=file_unit,file=filename) !open the file
n = count_lines_in_file(file_unit) !count lines in the file
allocate(dict(n)) !allocate dictionary structure
do i=1,n !
read(file_unit,'(A)') dict(i)%str !each line is a word in the dictionary
dict(i)%n = len_trim(dict(i)%str) !save word length
end do
close(file_unit) !close the file
!use elemental procedure to get ordered words:
dict%ordered = ordered_word(dict%str)
!max length of an ordered word:
n_max = maxval(dict%n, mask=dict%ordered)
!write the output:
do i=1,n
if (dict(i)%ordered .and. dict(i)%n==n_max) write(*,'(A,A)',advance='NO') trim(dict(i)%str),' '
end do
write(*,*) ''
!****************************************************
end program main
!****************************************************

View file

@ -0,0 +1,42 @@
' FB 1.05.0 Win64
Function isOrdered(s As Const String) As Boolean
If Len(s) <= 1 Then Return True
For i As Integer = 1 To Len(s) - 1
If s[i] < s[i - 1] Then Return False
Next
Return True
End Function
Dim words() As String
Dim word As String
Dim maxLength As Integer = 0
Dim count As Integer = 0
Open "undict.txt" For Input As #1
While Not Eof(1)
Line Input #1, word
If isOrdered(word) Then
If Len(word) = maxLength Then
Redim Preserve words(0 To count)
words(count) = word
count += 1
ElseIf Len(word) > maxLength Then
Erase words
maxLength = Len(word)
Redim words(0 To 0)
words(0) = word
count = 1
End If
End If
Wend
Close #1
Print "The ordered words with the longest length ("; Str(maxLength); ") in undict.txt are :"
Print
For i As Integer = 0 To UBound(words)
Print words(i)
Next
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,3 @@
url="https://web.archive.org/web/20180611003215if_/http://www.puzzlers.org:80/pub/wordlists/unixdict.txt"
a = sort[select[lines[url], {|w| charList[w] == sort[charList[w]] } ], {|a,b| length[a] <=> length[b]}]
println[sort[select[a, {|w, longest| length[w] == longest}, length[last[a]]]]]

View file

@ -0,0 +1,45 @@
local fn Words as CFArrayRef
CFURLRef url = fn URLWithString( @"https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt" )
CFStringRef string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
end fn = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet )
local fn IsOrderedWord( string as CFStringRef ) as BOOL
BOOL flag = YES
long i
unichar chr, prevChr = 0
for i = 0 to len(string) - 1
chr = fn StringCharacterAtIndex( string, i )
if ( chr < prevChr )
flag = NO : break
end if
prevChr = chr
next
end fn = flag
void local fn DoIt
CFStringRef string
CFArrayRef words = fn Words
long length, maxLen = 0
CFMutableStringRef orderedWords = fn MutableStringWithCapacity(0)
for string in words
length = len(string)
if ( length < maxLen ) then continue
if ( fn IsOrderedWord( string ) )
if ( length > maxLen )
MutableStringSetString( orderedWords, @"" )
maxLen = length
end if
MutableStringAppendFormat( orderedWords, @"%@\n", string )
end if
next
print orderedWords
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,30 @@
Public Sub Main()
Dim sDict As String = File.Load(User.Home &/ "unixdict.txt") 'Store the 'Dictionary'
Dim sOrdered As New String[] 'To store ordered words
Dim sHold As New String[] 'General store
Dim sTemp As String 'Temp variable
Dim siCount As Short 'Counter
For Each sTemp In Split(sDict, gb.NewLine) 'For each word in the Dictionary
For siCount = 1 To Len(sTemp) 'Loop for each letter in the word
sHold.Add(Mid(sTemp, siCount, 1)) 'Put each letter in sHold array
Next
sHold.Sort() 'Sort sHold (abbott = abboot, zoom = mooz)
If sTemp = sHold.Join("") Then sOrdered.Add(sTemp) 'If they are the same (abbott(OK) mooz(not OK)) then add to sOrdered
sHold.Clear 'Empty sHold
Next
siCount = 0 'Reset siCount
For Each sTemp In sOrdered 'For each of the Ordered words
If Len(sTemp) > siCount Then siCount = Len(sTemp) 'Count the length of the word and keep a record of the longest length
Next
For Each sTemp In sOrdered 'For each of the Ordered words
If Len(sTemp) = siCount Then sHold.Add(sTemp) 'If it is one of the longest add it to sHold
Next
sHold.Sort() 'Sort sHold
Print sHold.Join(gb.NewLine) 'Display the result
End

View file

@ -0,0 +1,57 @@
package main
import (
"bytes"
"fmt"
"io/ioutil"
)
func main() {
// read into memory in one chunk
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
fmt.Println(err)
return
}
// split at line ends
bss := bytes.Split(b, []byte{'\n'})
// accumulate result
var longest int
var list [][]byte
for _, bs := range bss {
// don't bother with words shorter than
// our current longest ordered word
if len(bs) < longest {
continue
}
// check for ordered property
var lastLetter byte
for i := 0; ; i++ {
if i == len(bs) {
// end of word. it's an ordered word.
// save it and break from loop
if len(bs) > longest {
longest = len(bs)
list = list[:0]
}
list = append(list, bs)
break
}
// check next letter
b := bs[i]
if b < 'a' || b > 'z' {
continue // not a letter. ignore.
}
if b < lastLetter {
break // word not ordered.
}
// letter passes test
lastLetter = b
}
}
// print result
for _, bs := range list {
fmt.Println(string(bs))
}
}

View file

@ -0,0 +1,9 @@
def isOrdered = { word -> def letters = word as List; letters == ([] + letters).sort() }
assert isOrdered('abbey')
assert !isOrdered('cat')
def dictUrl = new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt')
def orderedWords = dictUrl.readLines().findAll { isOrdered(it) }
def owMax = orderedWords*.size().max()
orderedWords.findAll { it.size() == owMax }.each { println it }

View file

@ -0,0 +1,19 @@
-- Words are read from the standard input. We keep in memory only the current
-- set of longest, ordered words.
--
-- Limitation: the locale's collation order is not take into consideration.
isOrdered wws@(_:ws) = and $ zipWith (<=) wws ws
longestOrderedWords = reverse . snd . foldl f (0,[]) . filter isOrdered
where f (max, acc) w =
let len = length w in
case compare len max of
LT -> (max, acc)
EQ -> (max, w:acc)
GT -> (len, [w])
main = do
str <- getContents
let ws = longestOrderedWords $ words str
mapM_ putStrLn ws

View file

@ -0,0 +1,16 @@
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty

View file

@ -0,0 +1,11 @@
import Control.Monad (liftM)
isSorted wws@(_ : ws) = and $ zipWith (<=) wws ws
getLines = liftM lines . readFile
main = do
ls <- getLines "unixdict.txt"
let ow = filter isSorted ls
let maxl = foldr max 0 (map length ow)
print $ filter (\w -> (length w) == maxl) ow

View file

@ -0,0 +1,25 @@
import Algorithms as algo;
import Mathematics as math;
import Network as net;
import Text as text;
main( argv_ ) {
url = size( argv_ ) > 1
? argv_[1]
: "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt";
words = algo.materialize( algo.map( net.get( url ).stream, string.strip ), list );
ordered = algo.materialize(
algo.filter(
words,
@( word ){ word == ∑( algo.map( algo.sorted( word ), string ) ); }
),
list
);
maxLen = algo.reduce( ordered, @( x, y ){ math.max( x, size( y ) ); }, 0 );
maxOrderedWords = algo.materialize(
algo.filter( ordered, @[maxLen]( word ){ size( word ) == maxLen; } ),
list
);
print( "{}\n".format( text.join( algo.sorted( maxOrderedWords ), " " ) ) );
return ( 0 );
}

View file

@ -0,0 +1,10 @@
link strings
procedure main(A)
f := open(\A[1]) | stop("Give dictionary file name on command line")
every (maxLen := 0, maxLen <= *(w := !f), w == csort(w)) do {
if maxLen <:= *w then maxList := [] #discard any shorter sorted words
put(maxList, w)
}
every write(!\maxList)
end

View file

@ -0,0 +1,17 @@
file := File clone openForReading("./unixdict.txt")
words := file readLines
file close
maxLen := 0
orderedWords := list()
words foreach(word,
if( (word size >= maxLen) and (word == (word asMutable sort)),
if( word size > maxLen,
maxLen = word size
orderedWords empty
)
orderedWords append(word)
)
)
orderedWords join(" ") println

View file

@ -0,0 +1,4 @@
NB. from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt
oWords=: (#~ ] = /:~L:0) cutLF fread 'unixdict.txt'
;:inv (#~ (= >./)@:(#@>)) oWords
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty

View file

@ -0,0 +1,43 @@
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Ordered {
private static boolean isOrderedWord(String word){
char[] sortedWord = word.toCharArray();
Arrays.sort(sortedWord);
return word.equals(new String(sortedWord));
}
public static void main(String[] args) throws IOException{
List<String> orderedWords = new LinkedList<String>();
BufferedReader in = new BufferedReader(new FileReader(args[0]));
while(in.ready()){
String word = in.readLine();
if(isOrderedWord(word)) orderedWords.add(word);
}
in.close();
Collections.<String>sort(orderedWords, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return new Integer(o2.length()).compareTo(o1.length());
}
});
int maxLen = orderedWords.get(0).length();
for(String word: orderedWords){
if(word.length() == maxLen){
System.out.println(word);
}else{
break;
}
}
}
}

View file

@ -0,0 +1,25 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public final class OrderedWords {
public static void main(String[] aArgs) throws IOException {
List<String> ordered = Files.lines(Path.of("unixdict.txt"))
.filter( word -> isOrdered(word) ).toList();
final int maxLength = ordered.stream().map( word -> word.length() ).max(Integer::compare).get();
ordered.stream().filter( word -> word.length() == maxLength ).forEach(System.out::println);
}
private static boolean isOrdered(String aWord) {
return aWord.chars()
.mapToObj( i -> (char) i )
.sorted()
.map(String::valueOf)
.reduce("", String::concat)
.equals(aWord);
}
}

View file

@ -0,0 +1,11 @@
var fs = require('fs'), print = require('sys').print;
fs.readFile('./unixdict.txt', 'ascii', function (err, data) {
var is_ordered = function(word){return word.split('').sort().join('') === word;},
ordered_words = data.split('\n').filter(is_ordered).sort(function(a, b){return a.length - b.length}).reverse(),
longest = [], curr = len = ordered_words[0].length, lcv = 0;
while (curr === len){
longest.push(ordered_words[lcv]);
curr = ordered_words[++lcv].length;
};
print(longest.sort().join(', ') + '\n');
});

View file

@ -0,0 +1,26 @@
var http = require('http');
http.get({
host: 'www.puzzlers.org',
path: '/pub/wordlists/unixdict.txt'
}, function(res) {
var data = '';
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
var words = data.split('\n');
var max = 0;
var ordered = [];
words.forEach(function(word) {
if (word.split('').sort().join('') != word) return;
if (word.length == max) {
ordered.push(word);
} else if (word.length > max) {
ordered = [word];
max = word.length;
}
});
console.log(ordered.join(', '));
});
});

View file

@ -0,0 +1,14 @@
def is_sorted:
if length <= 1 then true
else .[0] <= .[1] and (.[1:] | is_sorted)
end;
def longest_ordered_words:
# avoid string manipulation:
def is_ordered: explode | is_sorted;
map(select(is_ordered))
| (map(length)|max) as $max
| map( select(length == $max) );
split("\n") | longest_ordered_words

View file

@ -0,0 +1 @@
issorted("abc") # true

View file

@ -0,0 +1,4 @@
lst = readlines("data/unixdict.txt")
filter!(issorted, lst)
filter!(x -> length(x) == maximum(length, lst), lst)
println.(lst)

View file

@ -0,0 +1,17 @@
w@&d=|/d:#:'w:d@&&/'{~x<y}':'d:0:"unixdict.txt"
("abbott"
"accent"
"accept"
"access"
"accost"
"almost"
"bellow"
"billow"
"biopsy"
"chilly"
"choosy"
"choppy"
"effort"
"floppy"
"glossy"
"knotty")

View file

@ -0,0 +1,21 @@
import java.io.File
fun main(args: Array<String>) {
val file = File("unixdict.txt")
val result = mutableListOf<String>()
file.forEachLine {
if (it.toCharArray().sorted().joinToString(separator = "") == it) {
result += it
}
}
result.sortByDescending { it.length }
val max = result[0].length
for (word in result) {
if (word.length == max) {
println(word)
}
}
}

View file

@ -0,0 +1,44 @@
{def maxOrderedWords
{def isOrdered
{lambda {:w}
{W.equal? :w {W.sort before :w}}}}
{def getOrdered
{lambda {:w}
{if {isOrdered :w} then :w else}}}
{def pushOrdered
{lambda {:m :w}
{if {= {W.length :w} :m} then {br}:w else}}}
{def maxOrderedWords.i
{lambda {:sortedWords}
{let { {:orderedWords {S.map getOrdered :sortedWords}} }
{S.map {{lambda {:m :w} {pushOrdered :m :w}}
{max {S.map {lambda {:w} {W.length :w}}
:orderedWords}}}
:orderedWords}}}}
{lambda {:s}
{maxOrderedWords.i {S.replace else by el_se in :s}}}}
-> maxOrderedWords
{maxOrderedWords UNIX.DICT}
->
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty

View file

@ -0,0 +1,37 @@
: >string-index
"" split
"&'0123456789abcdefghijklmnopqrstuvwxyz" "" split
swap index collapse ;
: chars "" split length swap drop ;
: cr "\n" . ;
: nip swap drop ;
: ordered?
dup grade subscript != '+ reduce if 0 else -1 then ;
: filtering
[] '_ set
0 do read
2dup chars
<=
if dup >string-index ordered?
if 2dup chars
<
if nip dup chars swap
[] '_ set
then
_ swap append '_ set
'. . # progress dot
else drop
then
else drop
then
eof if break then loop
cr _ . cr
;
: ordered-words
'< 'unixdict.txt open 'fh set
fh fin filtering fh close ;
ordered-words

View file

@ -0,0 +1,18 @@
local(f = file('unixdict.txt'), words = array, ordered = array, maxleng = 0)
#f->dowithclose => {
#f->foreachLine => {
#words->insert(#1)
}
}
with w in #words
do => {
local(tosort = #w->asString->values)
#tosort->sort
if(#w->asString == #tosort->join('')) => {
#ordered->insert(#w->asString)
#w->asString->size > #maxleng ? #maxleng = #w->asString->size
}
}
with w in #ordered
where #w->size == #maxleng
do => {^ #w + '\r' ^}

View file

@ -0,0 +1,33 @@
'Ordered wordsFrom Rosetta Code
open "unixdict.txt" for input as #1
'this is not normal DOS/Windows file.
'It LF delimited, not CR LF
'So Line input would not work.
lf$=chr$(10)
curLen=0
wordList$=""
while not(eof(#1))
a$=inputto$(#1, lf$)
'now, check word
flag = 1
c$ = left$(a$,1)
for i = 2 to len(a$)
d$ = mid$(a$,i,1)
if c$>d$ then flag=0: exit for
c$=d$
next
'ckecked, proceed if ordered word
if flag then
if curLen=len(a$) then
wordList$=wordList$+" "+a$
else
if curLen<len(a$) then
curLen=len(a$)
wordList$=a$
end if
end if
end if
wend
close #1
print wordList$

View file

@ -0,0 +1,27 @@
-- Contents of unixdict.txt passed as string
on printLongestOrderedWords (words)
res = []
maxlen = 0
_player.itemDelimiter = numtochar(10)
cnt = words.item.count
repeat with i = 1 to cnt
w = words.item[i]
len = w.length
ordered = TRUE
repeat with j = 2 to len
if chartonum(w.char[j-1])>chartonum(w.char[j]) then
ordered = FALSE
exit repeat
end if
end repeat
if ordered then
if len > maxlen then
res = [w]
maxlen = len
else if len = maxlen then
res.add(w)
end if
end if
end repeat
put res
end

View file

@ -0,0 +1,29 @@
fp = io.open( "dictionary.txt" )
maxlen = 0
list = {}
for w in fp:lines() do
ordered = true
for l = 2, string.len(w) do
if string.byte( w, l-1 ) > string.byte( w, l ) then
ordered = false
break
end
end
if ordered then
if string.len(w) > maxlen then
list = {}
list[1] = w
maxlen = string.len(w)
elseif string.len(w) == maxlen then
list[#list+1] = w
end
end
end
for _, w in pairs(list) do
print( w )
end
fp:close()

View file

@ -0,0 +1,16 @@
maxlen = 0;
listlen= 0;
fid = fopen('unixdict.txt','r');
while ~feof(fid)
str = fgetl(fid);
if any(diff(abs(str))<0) continue; end;
if length(str)>maxlen,
list = {str};
maxlen = length(str);
elseif length(str)==maxlen,
list{end+1} = str;
end;
end
fclose(fid);
printf('%s\n',list{:});

View file

@ -0,0 +1,19 @@
lst := StringTools:-Split(Import("http://www.puzzlers.org/pub/wordlists/unixdict.txt"), "\n"):
longest := 0:
words := Array():
i := 1:
for word in lst do
if StringTools:-IsSorted(word) then
len := StringTools:-Length(word):
if len > longest then
longest := len:
words := Array():
words(1) := word:
i := 2:
elif len = longest then
words(i) := word:
i++:
end if;
end if;
end do;
for word in words do print(word); end do;

View file

@ -0,0 +1,5 @@
Module[{max,
data = Select[Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"],
OrderedQ[Characters[#]] &]},
max = Max[StringLength /@ data];
Select[data, StringLength[#] == max &]]

View file

@ -0,0 +1,3 @@
maxWords[language_String] := Module[{max,data = Select[DictionaryLookup[{language, "*"}],OrderedQ[Characters[#]] &]},
max = Max[StringLength /@ data];
Select[data, StringLength[#] == max &]]

View file

@ -0,0 +1,31 @@
import Nanoquery.IO
def is_ordered(word)
word = str(word)
if len(word) < 2
return true
end
for i in range(1, len(word) - 1)
if str(word[i]) < str(word[i - 1])
return false
end
end
return true
end
longest = 0
words = {}
for word in new(File, "unixdict.txt").read()
if is_ordered(word)
if len(word) > longest
longest = len(word)
words.clear()
words.append(word)
else if len(word) = longest
words.append(word)
end
end
end
println words

View file

@ -0,0 +1,39 @@
/* NetRexx */
options replace format comments java crossref savelog symbols binary
unixdict = 'unixdict.txt'
do
wmax = Integer.MIN_VALUE
dwords = ArrayList()
inrdr = BufferedReader(FileReader(File(unixdict)))
loop label ln while inrdr.ready
dword = Rexx(inrdr.readLine).strip
if isOrdered(dword) then do
dwords.add(dword)
if dword.length > wmax then
wmax = dword.length
end
end ln
inrdr.close
witerator = dwords.listIterator
loop label wd while witerator.hasNext
dword = Rexx witerator.next
if dword.length < wmax then do
witerator.remove
end
end wd
dwords.trimToSize
say dwords.toString
catch ex = IOException
ex.printStackTrace
end
return
method isOrdered(dword = String) inheritable static binary returns boolean
wchars = dword.toCharArray
Arrays.sort(wchars)
return dword.equalsIgnoreCase(String(wchars))

View file

@ -0,0 +1,22 @@
import strutils
const DictFile = "unixdict.txt"
func isSorted(s: string): bool =
var last = char.low
for c in s:
if c < last: return false
last = c
result = true
var
mx = 0
words: seq[string]
for word in DictFile.lines:
if word.len >= mx and word.isSorted:
if word.len > mx:
words.setLen(0)
mx = word.len
words.add word
echo words.join(" ")

View file

@ -0,0 +1,52 @@
let input_line_opt ic =
try Some(input_line ic)
with End_of_file -> None
(* load each line in a list *)
let read_lines ic =
let rec aux acc =
match input_line_opt ic with
| Some line -> aux (line :: acc)
| None -> (List.rev acc)
in
aux []
let char_list_of_string str =
let lst = ref [] in
String.iter (fun c -> lst := c :: !lst) str;
(List.rev !lst)
let is_ordered word =
let rec aux = function
| c1::c2::tl ->
if c1 <= c2
then aux (c2::tl)
else false
| c::[] -> true
| [] -> true (* should only occur with an empty string *)
in
aux (char_list_of_string word)
let longest_words words =
let res, _ =
List.fold_left
(fun (lst, n) word ->
let len = String.length word in
let comp = compare len n in
match lst, comp with
| lst, 0 -> ((word::lst), n) (* len = n *)
| lst, -1 -> (lst, n) (* len < n *)
| _, 1 -> ([word], len) (* len > n *)
| _ -> assert false
)
([""], 0) words
in
(List.rev res)
let () =
let ic = open_in "unixdict.txt" in
let words = read_lines ic in
let lower_words = List.map String.lowercase words in
let ordered_words = List.filter is_ordered lower_words in
let longest_ordered_words = longest_words ordered_words in
List.iter print_endline longest_ordered_words

View file

@ -0,0 +1,9 @@
: longWords
| w longest l s |
0 ->longest
File new("unixdict.txt") forEach: w [
w size dup ->s longest < ifTrue: [ continue ]
w sort w == ifFalse: [ continue ]
s longest > ifTrue: [ s ->longest ListBuffer new ->l ]
l add(w)
] l ;

View file

@ -0,0 +1,27 @@
/*REXX list (the longest) ordered word(s) from a supplied dictionary. */
iFID= 'UNIXDICT.TXT'
w.=''
mL=0
Do j=1 While lines(iFID)\==0
x=linein(iFID)
w=length(x)
If w>=mL Then Do
Parse Upper Var x xU 1 z 2
Do k=2 To w
_=substr(xU, k, 1)
If \datatype(_, 'U') Then Iterate
If _<z Then Iterate j
z=_
End
mL=w
w.w=w.w x
End
End
nn=words(w.mL)
Say nn 'word's(nn) "found (of length" mL')'
Say ''
Do n=1 To nn
Say word(w.mL, n)
End
Exit
s: Return left('s',arg(1)>1)

View file

@ -0,0 +1,4 @@
ordered(s)=my(v=Vecsmall(s),t=97);for(i=1,#v,if(v[i]>64&&v[i]<91,v[i]+=32);if(v[i]<97||v[i]>122||v[i]<t,return(0),t=v[i]));1
v=select(ordered,readstr("~/unixdict.txt"));
N=vecmax(apply(length,v));
select(s->#s==N, v)

View file

@ -0,0 +1,55 @@
order: procedure options (main); /* 24/11/2011 */
declare word character (20) varying;
declare word_list character (20) varying controlled;
declare max_length fixed binary;
declare input file;
open file (input) title ('/ORDER.DAT,TYPE(TEXT),RECSIZE(100)');
on endfile (input) go to completed_search;
max_length = 0;
do forever;
get file (input) edit (word) (L);
if length(word) > max_length then
do;
if in_order(word) then
do;
/* Get rid of any stockpiled shorter words. */
do while (allocation(word_list) > 0);
free word_list;
end;
/* Add the eligible word to the stockpile. */
allocate word_list;
word_list = word;
max_length = length(word);
end;
end;
else if max_length = length(word) then
do; /* we have an eligle word of the same (i.e., maximum) length. */
if in_order(word) then
do; /* Add it to the stockpile. */
allocate word_list;
word_list = word;
end;
end;
end;
completed_search:
put skip list ('There are ' || trim(allocation(word_list)) ||
' eligible words of length ' || trim(length(word)) || ':');
do while (allocation(word_list) > 0);
put skip list (word_list);
free word_list;
end;
/* Check that the letters of the word are in non-decreasing order of rank. */
in_order: procedure (word) returns (bit(1));
declare word character (*) varying;
declare i fixed binary;
do i = 1 to length(word)-1;
if substr(word, i, 1) > substr(word, i+1, 1) then return ('0'b);
end;
return ('1'b);
end in_order;
end order;

View file

@ -0,0 +1,12 @@
#!/usr/bin/perl
use strict;
use warnings;
open(FH, "<", "unixdict.txt") or die "Can't open file!\n";
my @words;
while (<FH>) {
chomp;
push @{$words[length]}, $_ if $_ eq join("", sort split(//));
}
close FH;
print "@{$words[-1]}\n";

View file

@ -0,0 +1,15 @@
(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: #004080;">integer</span> <span style="color: #000000;">maxlen</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">word</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">maxlen</span> <span style="color: #008080;">and</span> <span style="color: #000000;">word</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">></span><span style="color: #000000;">maxlen</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">found</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxlen</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l</span><span style="color: #0000FF;">}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">found</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">found</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">word</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">"The %d longest ordered words:\n %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">found</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">found</span><span style="color: #0000FF;">],</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n "</span><span style="color: #0000FF;">)})</span>
<!--

View file

@ -0,0 +1,27 @@
include ..\Utilitys.pmt
0 var maxlen
( ) var words
0 var f
def getword f fgets dup -1 == if drop false else -1 del endif enddef
def ordered? dup dup sort == enddef
def greater? len maxlen > enddef
"unixdict.txt" "r" fopen var f
f -1 !=
while
getword dup if
ordered? if
greater? if
len var maxlen
( ) var words
endif
len maxlen == if
words over 0 put var words
endif
endif
endif
endwhile
f fclose
words print

View file

@ -0,0 +1,27 @@
include ..\Utilitys.pmt
0 var f
def getword f fgets dup -1 == if drop false else -1 del endif enddef
def ordered? dup dup sort == enddef
def greater? len rot 1 get len nip rot swap over over > enddef
def append over 0 put enddef
( " " )
"unixdict.txt" "r" fopen var f
f -1 !=
while
getword dup if
ordered? if
greater? if
drop drop flush append
else
== if append endif
endif
swap
endif
endif
endwhile
f fclose
print

View file

@ -0,0 +1,5 @@
go =>
Dict = "unixdict.txt",
Words = new_map([Word=Word.length : Word in read_file_lines(Dict), Word == Word.sort()]),
MaxLen = max([Len : _Word=Len in Words]),
println([Word : Word=Len in Words, Len=MaxLen].sort).

View file

@ -0,0 +1,6 @@
(in "unixdict.txt"
(mapc prinl
(maxi '((L) (length (car L)))
(by length group
(filter '((S) (apply <= S))
(make (while (line) (link @))) ) ) ) ) )

View file

@ -0,0 +1,16 @@
$url = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
(New-Object System.Net.WebClient).DownloadFile($url, "$env:TEMP\unixdict.txt")
$ordered = Get-Content -Path "$env:TEMP\unixdict.txt" |
ForEach-Object {if (($_.ToCharArray() | Sort-Object) -join '' -eq $_) {$_}} |
Group-Object -Property Length |
Sort-Object -Property Name |
Select-Object -Property @{Name="WordCount" ; Expression={$_.Count}},
@{Name="WordLength"; Expression={[int]$_.Name}},
@{Name="Words" ; Expression={$_.Group}} -Last 1
"There are {0} ordered words of the longest word length ({1} characters):`n`n{2}" -f $ordered.WordCount,
$ordered.WordLength,
($ordered.Words -join ", ")
Remove-Item -Path "$env:TEMP\unixdict.txt" -Force -ErrorAction SilentlyContinue

View file

@ -0,0 +1,44 @@
:- use_module(library( http/http_open )).
ordered_words :-
% we read the URL of the words
http_open('http://www.puzzlers.org/pub/wordlists/unixdict.txt', In, []),
read_file(In, [], Out),
close(In),
% we get a list of pairs key-value where key = Length and value = <list-of-its-codes>
% this list must be sorted
msort(Out, MOut),
group_pairs_by_key(MOut, POut),
% we sorted this list in decreasing order of the length of values
predsort(my_compare, POut, [_N-V | _OutSort]),
maplist(mwritef, V).
mwritef(V) :-
writef('%s\n', [V]).
read_file(In, L, L1) :-
read_line_to_codes(In, W),
( W == end_of_file ->
% the file is read
L1 = L
;
% we sort the list of codes of the line
% and keep only the "goods word"
( msort(W, W) ->
length(W, N), L2 = [N-W | L], (len = 6 -> writef('%s\n', [W]); true)
;
L2 = L
),
% and we have the pair Key-Value in the result list
read_file(In, L2, L1)).
% predicate for sorting list of pairs Key-Values
% if the lentgh of values is the same
% we sort the keys in alhabetic order
my_compare(R, K1-_V1, K2-_V2) :-
( K1 < K2 -> R = >; K1 > K2 -> R = <; =).

View file

@ -0,0 +1,46 @@
Procedure.s sortLetters(*word.Character, wordLength) ;returns a string with the letters of a word sorted
Protected Dim letters.c(wordLength)
Protected *letAdr = @letters()
CopyMemoryString(*word, @*letAdr)
SortArray(letters(), #PB_Sort_Ascending, 0, wordLength - 1)
ProcedureReturn PeekS(@letters(), wordLength)
EndProcedure
Structure orderedWord
word.s
length.i
EndStructure
Define filename.s = "unixdict.txt", fileNum = 0, word.s
If OpenConsole()
NewList orderedWords.orderedWord()
If ReadFile(fileNum, filename)
While Not Eof(fileNum)
word = ReadString(fileNum)
If word = sortLetters(@word, Len(word))
AddElement(orderedWords())
orderedWords()\word = word
orderedWords()\length = Len(word)
EndIf
Wend
Else
MessageRequester("Error", "Unable to find dictionary '" + filename + "'")
End
EndIf
SortStructuredList(orderedWords(), #PB_Sort_Ascending, OffsetOf(orderedWord\word), #PB_String)
SortStructuredList(orderedWords(), #PB_Sort_Descending, OffsetOf(orderedWord\length), #PB_Integer)
Define maxLength
FirstElement(orderedWords())
maxLength = orderedWords()\length
ForEach orderedWords()
If orderedWords()\length = maxLength
Print(orderedWords()\word + " ")
EndIf
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf

Some files were not shown because too many files have changed in this diff Show more