Ordered words: Difference between revisions
Add Uiua
m (→{{header|jq}}: map(select(_))) |
(Add Uiua) |
||
(138 intermediate revisions by 72 users not shown) | |||
Line 1:
{{task|text processing}}
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>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">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(‘ ’))</syntaxhighlight>
{{out}}
<pre>
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
</pre>
=={{header|Acornsoft Lisp}}==
In <code>find-longest-ordered-words</code>, <code>len</code>, <code>word</code>, and <code>words</code> are used as local variables. <code>open</code> returns an integer as a file-handle. <code>chars</code> returns the number of characters in a symbol's name. <code>eq</code> can be used to compare numbers for equality.
<syntaxhighlight lang="lisp">
(defun longest-ordered-words ()
(find-longest-ordered-words
(open 'notes/unixdict!.txt t)))
(defun find-longest-ordered-words
(h (len . 0) (word) (words))
(loop
(until (eof h)
(close h)
words)
(setq word (readline h))
(cond ((lessp (chars word) len))
((not (ordered-p word)))
((eq (chars word) len)
(setq words (cons word words)))
(t
(setq len (chars word))
(setq words (list word))))))
(defun ordered-p (word)
(nondecreasing-p
(mapc ordinal (explode word))))
(defun nondecreasing-p (numbers)
(or (null numbers)
(null (cdr numbers))
(and (not (greaterp (car numbers) (cadr numbers)))
(nondecreasing-p (cdr numbers)))))
</syntaxhighlight>
{{Out}}
<code>(longest-ordered-words)</code> will return
<pre>
(knotty glossy floppy effort
choppy choosy chilly biopsy
billow bellow almost accost
access accept accent abbott)
</pre>
=={{header|Action!}}==
In the following solution the input file is loaded from H6 drive. Altirra emulator automatically converts CR/LF character from ASCII into 155 character in ATASCII charset used by Atari 8-bit computer when one from H6-H10 hard drive under DOS 2.5 is used.
<syntaxhighlight lang="action!">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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Ordered_words.png Screenshot from Atari 8-bit computer]
<pre>
Finding the longest words...
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
</pre>
=={{header|Ada}}==
<syntaxhighlight lang="ada">
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
while not
declare
begin
if
if
Max_Length :=
elsif
end if;
end if;
end;
end loop;
Put_Line (Word);
end loop;
Close (File);
end Ordered_Words;
</syntaxhighlight>
Output:
Line 74 ⟶ 203:
=={{header|Aime}}==
<
ordered(
{
integer a,
a = 1;
} else {
}
}
}
Line 100 ⟶ 226:
main(void)
{
file f;
text s;
index x;
if (ordered(s)) {
x.v_list(~s).append(s);
}
}
return 0;
}</
{{out}}
<pre>abbott
Line 148 ⟶ 259:
glossy
knotty</pre>
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}.
<syntaxhighlight lang="algol68">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</syntaxhighlight>
{{out}}
<pre>Maximum length of ordered words: 6
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <basico.h>
#define MAX_LINE 30
algoritmo
fd=0
word={}, result={}
old_word="",new_word=""
fijar separador (NULO)
abrir para leer("basica/unixdict.txt",fd)
iterar mientras ' no es fin de archivo (fd) '
usando 'MAX_LINE', leer línea desde(fd),
---copiar en 'old_word'---, separar para 'word '
word, ---retener--- ordenar esto,
encadenar en 'new_word'
new_word, meter según (#(old_word == new_word), result)
reiterar
cerrar archivo(fd)
result ---retener---, obtener largo ---retener---
obtener máximo valor, es mayor o igual?, replicar esto
compactar esto
fijar separador 'NL', luego imprime todo
terminar
</syntaxhighlight>
{{out}}
<pre>
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
</pre>
=={{header|APL}}==
Works in NARS2000 APL; ("Objects" menu -> New, paste this in, save. Then run in the main session manager).
<syntaxhighlight lang="apl">result←longest_ordered_words file_path
f←file_path ⎕NTIE 0 ⍝ open file
text←⎕NREAD f 'char8' ⍝ read vector of 8bit chars
⎕NUNTIE f ⍝ close file
lines←text⊂⍨~text∊(⎕UCS 10 13) ⍝ split into lines (\r\n)
⍝ filter only words with ordered characters
ordered_words←lines/⍨{(⍳∘≢≡⍋)⍵}¨lines
⍝ find max of word lengths, filter only words with that length
result←ordered_words/⍨lengths=⍨⌈/lengths←≢¨ordered_words
</syntaxhighlight>
The ordered character filter is a train which uses gradeup to say which order you would have to pick the characters, to put them in order. e.g. ⍋ 'zxy' is 2 3 1 because you'd have to pick the second character, then the third, then the first, to put them in order. If they are in order then the result is the integers 1 2 3 .. to the length of the word.
And it generates the integers up to the length of the word, e.g. 1 2 3. and compares if those two arrays are the same.
Then uses that information as a filter against the original word list.
The result is: lengths of each ordered word, which equal the max-reduce of the list of lengths (longest word), used as a filter against the ordered word list.
{{out}}
<pre>
longest_ordered_words 'd:\unixdict.txt'
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
</pre>
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">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</syntaxhighlight>
{{output}}
<syntaxhighlight lang="applescript">{"abbott", "accent", "accept", "access", "accost", "almost", "bellow", "billow", "biopsy", "chilly", "choosy", "choppy", "effort", "floppy", "glossy", "knotty"}</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">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</syntaxhighlight>
{{out}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</pre>
=={{header|AutoHotkey}}==
Line 153 ⟶ 486:
StringLower could be used. This script assumes a locally downloaded copy of the dictionary, but UrlDownloadToFile could be used.
The purpose of the GUI is simply to display a field where the user can copy the list. MsgBox could be used, or FileAppend.
<syntaxhighlight lang="autohotkey">
MaxLen=0
Loop, Read, UnixDict.txt ; Assigns A_LoopReadLine to each line of the file
Line 187 ⟶ 520:
GUIClose:
ExitApp
</syntaxhighlight>
Output:
<pre>abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty</pre>
=={{header|AWK}}==
<
abc = "abcdefghijklmnopqrstuvwxyz"
}
Line 226 ⟶ 560:
for (i = 1; i <= best["count"]; i++)
print best[i]
}</
You must provide <tt>unixdict.txt</tt> as input.
<pre>$ awk -f ordered-words.awk unixdict.txt
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|BaCon}}==
<syntaxhighlight lang="freebasic">'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$
</syntaxhighlight>
{{out}}
<pre>prompt$ bacon ordered-words
Converting 'ordered-words.bac'... done, 29 lines were processed in 0.004 seconds.
Compiling 'ordered-words.bac'... cc -c ordered-words.bac.c
cc -o ordered-words ordered-words.bac.o -lbacon -lm
Done, program 'ordered-words' ready.
prompt$ ./ordered-words
abbott
accent
Line 250 ⟶ 631:
=={{header|BBC BASIC}}==
An optimisation is that the word isn't checked for being ordered unless it is at least as long as the current maximum.
<
IF dict%=0 ERROR 100, "Failed to open dictionary file"
Line 268 ⟶ 649:
CLOSE #dict%
PRINT list$
END</
'''Output:'''
<pre>
Line 289 ⟶ 670:
</pre>
=={{header|Befunge}}==
The word list is read from stdin, so ideally requires an interpreter that can accept input redirected from a file. It's still possible to enter the test data manually, though - you would just need to mark the end of the list with a blank line.
Memory usage isn't very efficient - the matching list is stored one word per line - so on a standard Befunge-93 interpreter there is an upper limit of 22 matches. This is not a problem for the unix dictionary, which only requires 16, but it's theoretically possible that other data sets could run out of space.
<syntaxhighlight lang="befunge">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#<*#<_</syntaxhighlight>
{{out}}
<pre>abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|BQN}}==
<code>(↕∘≠≡⍋)</code> checks for an ordered word.
<code>¯1⊑(≠¨⊔⊢)</code> groups by length, and takes the last (longest length) group.
<syntaxhighlight lang="bqn"> words←•FLines "unixdict.txt"
¯1⊑(≠¨⊔⊢)(↕∘≠≡⍋)¨⊸/words
⟨ "abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow" "biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty" ⟩</syntaxhighlight>
=={{header|Bracmat}}==
<
= bow result longestLength word character
. 0:?bow
Line 314 ⟶ 730:
| !result
)
& orderedWords$"unixdict.txt"</
<pre> knotty
glossy
Line 333 ⟶ 749:
=={{header|Burlesque}}==
<
{{Out}}
Line 355 ⟶ 771:
=={{header|C}}==
<
#include <string.h>
#include <stdio.h>
Line 437 ⟶ 853:
return EXIT_SUCCESS;
}</
Output:
<pre>abbott
Line 456 ⟶ 872:
knotty</pre>
Alternative version with dynamic array:
<
#include <string.h>
#include <stdio.h>
Line 542 ⟶ 958:
return EXIT_SUCCESS;
}</
===Mmap===
Shorter and potentially much faster version with <code>mmap (2)</code>. No stinky <code>malloc</code> or <code>scanf</code> calls.
<
#include <sys/mman.h>
#include <sys/types.h>
Line 598 ⟶ 1,014:
close(fd);
return 0;
}</
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">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;
}
}</syntaxhighlight>
Output:
<pre>abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty</pre>
=={{header|C++}}==
<
#include <fstream>
#include <iostream>
Line 639 ⟶ 1,090:
}
std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}</
Output:
<pre>
Line 659 ⟶ 1,110:
knotty
</pre>
=={{header|Clojure}}==
<
(not-any? pos? (map compare coll (next coll))))
Line 712 ⟶ 1,127:
take-while-eqcount
(clojure.string/join ", ")
println))</
Output
<
=={{header|CLU}}==
<syntaxhighlight lang="clu">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</syntaxhighlight>
{{out}}
<pre>accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> 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.</syntaxhighlight>
{{out}}
<pre>abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|CoffeeScript}}==
<
ordered_word = (word) ->
for i in [0...word.length - 1]
Line 740 ⟶ 1,301:
dict_words = file_content.toString().split '\n'
show_longest_ordered_words dict_words, dict_file_name
</syntaxhighlight>
output
<syntaxhighlight lang="text">
> coffee ordered_words.coffee
Longest Ordered Words (source=unixdict.txt):
Line 761 ⟶ 1,322:
glossy
knotty
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(reduce (lambda (prev curr)
(when (char> prev curr) (return-from orderedp nil))
Line 790 ⟶ 1,351:
("abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow"
"biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty")
</syntaxhighlight>
Or in a more functional way:
<syntaxhighlight lang="lisp">(defun orderedp (word)
(apply #'char<= (coerce word 'list)))
(let* ((words (uiop:read-file-lines "unixdict.txt"))
(ordered (delete-if-not #'orderedp words))
(maxlen (apply #'max (mapcar #'length ordered)))
(result (delete-if-not (lambda (l) (= l maxlen)) ordered :key #'length)))
(format t "~{~A~^, ~}" result))</syntaxhighlight>
{{out}}
<pre>abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty</pre>
=={{header|Cowgol}}==
Because Cowgol is meant to run on small systems, this program does not store the words
in memory. Instead, it scans through the file twice; once to find the maximum length
of the ordered words it finds, and once to actually print the words.
<syntaxhighlight lang="cowgol">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);</syntaxhighlight>
{{out}}
<pre>abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|D}}==
===Simple Procedural Version===
<
import std.stdio, std.algorithm, std.range, std.string;
Line 813 ⟶ 1,493:
writefln("%-(%s\n%)", result);
}</
{{out}}
<pre>abbott
Line 834 ⟶ 1,514:
===Faster Procedural Version===
Faster, same output.
<
import std.stdio, std.algorithm, std.file, std.range;
Line 852 ⟶ 1,532:
writefln("%-(%s\n%)", result);
}</
===Functional Version===
Shorter, same output.
<
import std.stdio, std.algorithm, std.range, std.file, std.string;
Line 862 ⟶ 1,542:
immutable maxLen = words.map!q{a.length}.reduce!max;
writefln("%-(%s\n%)", words.filter!(w => w.length == maxLen));
}</
===Fastest Memory Mapped Version===
Lower level, much faster with large input files (about as fast as the memory mapped C version). The output is the same. It works only with ASCII texts, but unlike the C entry this is portable.
{{trans|C}}
<
const(char)[] findWord(const char[] s) pure nothrow @safe @nogc {
Line 907 ⟶ 1,587:
txt[0 .. outStart].write;
}</
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
program POrderedWords;
Line 965 ⟶ 1,645:
end;
end.
</syntaxhighlight>
Output: dictionary directly processed from the URL
<syntaxhighlight lang="delphi">
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
</syntaxhighlight>
=={{header|Draco}}==
<syntaxhighlight lang="draco">\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</syntaxhighlight>
{{out}}
<pre>abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|E}}==
{{trans|Python}}
<
def words := <http://www.puzzlers.org/pub/wordlists/unixdict.txt>.getText().split("\n")
Line 982 ⟶ 1,717:
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))</
One-pass procedural algorithm which avoids keeping the entire data set in memory:
<
for `@word$\n` ? (word.sort() <=> word) in <http://www.puzzlers.org/pub/wordlists/unixdict.txt> {
if (best.size() == 0) {
Line 996 ⟶ 1,731:
}
}
println(" ".rjoin(best.snapshot()))</
Output: <code>abbott accent accept access accost almost bellow billow biopsy chilly choosy
choppy effort floppy glossy knotty</code>
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(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)
</syntaxhighlight>
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">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)</syntaxhighlight>
{{out}}
<pre>
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
</pre>
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( ordered_words ).
Line 1,023 ⟶ 1,819:
words() -> anagrams_deranged:words_from_url( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ).
</syntaxhighlight>
{{out}}
<pre>
Line 1,033 ⟶ 1,829:
=={{header|Euphoria}}==
<
type ordered(sequence s)
Line 1,068 ⟶ 1,864:
close(fn)
pretty_print(1,words,{2})</
Output:
Line 1,091 ⟶ 1,887:
=={{header|F Sharp|F#}}==
<
open System.IO
Line 1,103 ⟶ 1,899:
|> Seq.head |> snd
longestOrderedWords() |> Seq.iter (printfn "%s")</
Output:
Line 1,125 ⟶ 1,921:
=={{header|Factor}}==
<
USING: grouping http.client io io.encodings.utf8 io.files
io.files.temp kernel math memoize sequences sequences.extras
Line 1,143 ⟶ 1,939:
word-list [ ordered-word? ] filter
all-longest [ print ] each ;
</syntaxhighlight>
Output: <pre>( scratchpad ) USING: ordered-words-main ;
Line 1,166 ⟶ 1,962:
=={{header|Fantom}}==
<
class Main
{
Line 1,197 ⟶ 1,993:
}
}
</syntaxhighlight>
Output:
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
</pre>
=={{header|FBSL}}==
Downloads the list from puzzlers.org.
<
FUNCTION RESTfulGET(url)
Line 1,237 ⟶ 2,034:
RETURN TRUE
END FUNCTION
</syntaxhighlight>
Output
<pre> abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
Line 1,247 ⟶ 2,044:
This program uses a string stack, which means that all matching words are stored on a stack.
The longest word ends up on the top of the stack.
<syntaxhighlight lang="forth">
include lib/stmstack.4th \ include string stack library
Line 1,291 ⟶ 2,088:
; \ open file, clear the stack, read file
\ read it back and close the file
ordered</
Since the longest word is on top of the stack, the only thing to be done is to pop
all words from the stack until a shorter word is encountered. Consequently, all
Line 1,314 ⟶ 2,111:
=={{header|Fortran}}==
<
!***************************************************************************************
module ordered_module
Line 1,428 ⟶ 2,225:
end program main
!****************************************************
</syntaxhighlight>
'''Output'''
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty </pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' 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</syntaxhighlight>
{{out}}
<pre>
The ordered words with the longest length (6) in undict.txt are :
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
</pre>
=={{header|Frink}}==
<syntaxhighlight lang="frink">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]]]]]</syntaxhighlight>
{{out}}
<pre>
[abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty]
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
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
</syntaxhighlight>
=={{header|Gambas}}==
<syntaxhighlight lang="gambas">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 </syntaxhighlight>
Output:
<pre>
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
</pre>
=={{header|Go}}==
Go has strings and Unicode and stuff, but with the dictionary all ASCII
and lower case, strings and Unicode seem overkill. I just worked with byte slices here, only converting the final result to strings for easy output.
<
import (
Line 1,491 ⟶ 2,466:
fmt.Println(string(bs))
}
}</
Output:
<pre>
Line 1,514 ⟶ 2,489:
=={{header|Groovy}}==
Solution:
<
assert isOrdered('abbey')
assert !isOrdered('cat')
Line 1,522 ⟶ 2,497:
def owMax = orderedWords*.size().max()
orderedWords.findAll { it.size() == owMax }.each { println it }</
Output:
Line 1,541 ⟶ 2,516:
glossy
knotty</pre>
=={{header|Haskell}}==
<
-- Words are read from the standard input. We keep in memory only the current
-- set of longest, ordered words.
Line 1,562 ⟶ 2,538:
let ws = longestOrderedWords $ words str
mapM_ putStrLn ws
</syntaxhighlight>
Output:
<
abbott
accent
Line 1,582 ⟶ 2,558:
glossy
knotty
</syntaxhighlight>
Alternative version:
<
isSorted wws@(_ : ws) = and $ zipWith (<=) wws ws
Line 1,594 ⟶ 2,570:
let ow = filter isSorted ls
let maxl = foldr max 0 (map length ow)
print $ filter (\w -> (length w) == maxl) ow</
=={{header|Huginn}}==
<syntaxhighlight lang="huginn">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 );
}</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main(A)
Line 1,606 ⟶ 2,609:
}
every write(!\maxList)
end</
{{libheader|Icon Programming Library}}
Line 1,630 ⟶ 2,633:
knotty
-></pre>
=={{header|Io}}==
<syntaxhighlight lang="io">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</syntaxhighlight>
{{output}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
</pre>
=={{header|J}}==
<syntaxhighlight lang="j">NB. from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</syntaxhighlight>
Recap:
#
# break into words, one per line (<code>
# find ordered words (<code>
# select the longest ordered words (<code>(#~ (= >./)@:(#@>))oWords</code>)
# format for display (using ;:inv)
=={{header|Java}}==
{{works with|Java|1.5+}}
This example assumes there is a local copy of the dictionary whose path is given as the first argument to the program.
<
import java.io.FileReader;
import java.io.IOException;
Line 1,690 ⟶ 2,715:
}
}
}</
Output:
<pre>abbott
Line 1,708 ⟶ 2,733:
glossy
knotty</pre>
===Using Java 16===
<syntaxhighlight lang="java">
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);
}
}
</syntaxhighlight>
<pre>
The same as the Java example above.
</pre>
=={{header|JavaScript}}==
Using [http://nodejs.org/ node.js]:
<
fs.readFile('./unixdict.txt', 'ascii', function (err, data) {
var is_ordered = function(word){return word.split('').sort().join('') === word;},
Line 1,722 ⟶ 2,780:
};
print(longest.sort().join(', ') + '\n');
});</
Output:
Line 1,729 ⟶ 2,787:
Alternative version (also using Node.js):
<
http.get({
Line 1,754 ⟶ 2,812:
console.log(ordered.join(', '));
});
});</
=={{header|jq}}==
{{works with|jq|1.4}}
<syntaxhighlight lang="jq">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
Line 1,777 ⟶ 2,829:
split("\n") | longest_ordered_words</
{{out}}
["abbott","accent","accept","access","accost","almost","bellow","billow","biopsy","chilly","choosy","choppy","effort","floppy","glossy","knotty"]
=={{header|Julia}}==
{{works with|Julia|0.6}}
'''
<syntaxhighlight lang="julia">issorted("abc") # true</syntaxhighlight>
'''Main''':
<syntaxhighlight lang="julia">lst = readlines("data/unixdict.txt")
filter!(issorted, lst)
filter!(x -> length(x) == maximum(length, lst), lst)
println.(lst)</syntaxhighlight>
{{out}}
<pre>abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|K}}==
<
("abbott"
"accent"
Line 1,856 ⟶ 2,880:
"floppy"
"glossy"
"knotty")</
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import java.net.URI
fun main() {
val url = URI(
"https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"
).toURL()
val words = url.openStream().bufferedReader().use {
var max = 0
it.lineSequence()
.filter { it.asSequence().windowed(2).all { it[0] <= it[1] } }
.sortedByDescending(String::length)
.takeWhile { word -> word.length >= max.also { max = word.length } }
.toList()
}
words.forEach(::println)
}
</syntaxhighlight>
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{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
</syntaxhighlight>
=={{header|Lang5}}==
<
"" split
"&'0123456789abcdefghijklmnopqrstuvwxyz" "" split
Line 1,895 ⟶ 2,987:
fh fin filtering fh close ;
ordered-words</
{{out}}
<pre>[ abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty ]</pre>
=={{header|Lasso}}==
<
#f->dowithclose => {
#f->foreachLine => {
Line 1,918 ⟶ 3,009:
with w in #ordered
where #w->size == #maxleng
do => {^ #w + '\r' ^}</
{{out}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</pre>
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
'Ordered wordsFrom Rosetta Code
open "unixdict.txt" for input as #1
Line 1,957 ⟶ 3,048:
close #1
print wordList$
</syntaxhighlight>
Output:
Line 1,976 ⟶ 3,067:
glossy
knotty </pre>
=={{header|Lingo}}==
Code ported from Lua solution.
<syntaxhighlight lang="lingo">-- 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</syntaxhighlight>
{{Out}}
<pre>-- ["abbott", "accent", "accept", "access", "accost", "almost", "bellow", "billow", "biopsy", "chilly", "choosy", "choppy", "effort", "floppy", "glossy", "knotty"]</pre>
=={{header|Lua}}==
<
maxlen = 0
Line 2,006 ⟶ 3,129:
end
fp:close()</
Output:
<pre>abbott
Line 2,025 ⟶ 3,148:
knotty</pre>
=={{header|Maple}}==
<syntaxhighlight lang="maple">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;</syntaxhighlight>
{{Out|Output}}
<pre>"abbott"
"accent"
"accept"
"access"
"accost"
"almost"
"bellow"
"billow"
"biopsy"
"chilly"
"choosy"
"choppy"
"effort"
"floppy"
"glossy"
"knotty"</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
data = Select[Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"],
OrderedQ[Characters[#]] &]},
max = Max[StringLength /@ data];
Select[data, StringLength[#] == max &]]
</syntaxhighlight>
However Mathematica has built in dictionaries for many languages, so here is a more general version...
<
max = Max[StringLength /@ data];
Select[data, StringLength[#] == max &]]
</syntaxhighlight>
<pre>
Line 2,054 ⟶ 3,214:
=={{header|MATLAB}} / {{header|Octave}}==
<
listlen= 0;
fid = fopen('unixdict.txt','r');
Line 2,069 ⟶ 3,229:
end
fclose(fid);
printf('%s\n',list{:}); </
Returns:
Line 2,088 ⟶ 3,248:
glossy
knotty</pre>
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">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</syntaxhighlight>
{{out}}
<pre>[abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty]</pre>
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols binary
Line 2,129 ⟶ 3,325:
Arrays.sort(wchars)
return dword.equalsIgnoreCase(String(wchars))
</syntaxhighlight>
;Output
<pre>
Line 2,136 ⟶ 3,332:
=={{header|Nim}}==
<syntaxhighlight lang
const DictFile = "unixdict.txt"
func isSorted(s: string): bool =
var last = char.low
for c in s:
if c < last: return false
last = c
var
for word in
if word.len >= mx and
if word.len > mx:
words
mx = word.len
words.add
echo words.join(" ")</
{{out}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</pre>
=={{header|OCaml}}==
<
try Some(input_line ic)
with End_of_file -> None
Line 2,213 ⟶ 3,410:
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</
Output:
Line 2,237 ⟶ 3,434:
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">: longWords
| w longest l s |
0 ->longest
File
w size dup ->s longest < ifTrue: [ continue ]
w sort w == ifFalse: [ continue ]
s longest > ifTrue: [ s ->longest ListBuffer new ->l ]
l add(w)
] l ; </syntaxhighlight>
{{out}}
<pre>
>longWords .
[abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty]
</pre>
=={{header|ooRexx}}==
{{trans|REXX}}
Adapted for ooRexx
<syntaxhighlight lang="oorexx">/*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)</syntaxhighlight>
{{out}}
Same as REXX'
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">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)</syntaxhighlight>
{{out}}
<pre>%1 = ["abbott", "accent", "accept", "access", "accost", "almost", "bellow", "billow", "biopsy", "chilly", "choosy", "choppy", "effort", "floppy", "glossy", "knotty"]</pre>
=={{header|Perl}}==
<
use strict;
use warnings;
Line 2,269 ⟶ 3,504:
close FH;
print "@{$words[-1]}\n";
</syntaxhighlight>
Output:
<pre>
Line 2,275 ⟶ 3,510:
</pre>
=={{header|
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">unix_dict</span><span style="color: #0000FF;">()</span>
<span style="color: #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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
The 16 longest ordered words:
abbott accent accept access
accost almost bellow billow
biopsy chilly choosy choppy
effort floppy glossy knotty
</pre>
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">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</syntaxhighlight>
Another solution
<syntaxhighlight lang="phixmonti">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</syntaxhighlight>
{{out}}
<pre>
["abbott", "accent", "accept", "access", "accost", "almost", "bellow", "billow", "biopsy", "chilly", "choosy", "choppy", "effort", "floppy", "glossy", "knotty"]
</pre>
=={{header|Picat}}==
<syntaxhighlight lang="picat">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).</syntaxhighlight>
{{out}}
<pre>[abbott,accent,accept,access,accost,almost,bellow,billow,biopsy,chilly,choosy,choppy,effort,floppy,glossy,knotty]</pre>
=={{header|PicoLisp}}==
<
(mapc prinl
(maxi '((L) (length (car L)))
(by length group
(filter '((S) (apply <= S))
(make (while (line) (link @))) ) ) ) ) )</
Output:
<pre>abbott
Line 2,309 ⟶ 3,632:
=={{header|PL/I}}==
<
order: procedure options (main); /* 24/11/2011 */
declare word character (20) varying;
Line 2,365 ⟶ 3,688:
end in_order;
end order;
</syntaxhighlight>
OUTPUT:
<pre>
Line 2,385 ⟶ 3,708:
accent
abbott
</pre>
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
$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
</syntaxhighlight>
{{Out}}
<pre>
There are 16 ordered words of the longest word length (6 characters):
abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty
</pre>
Line 2,390 ⟶ 3,740:
Works with SWI-Prolog
<
ordered_words :-
Line 2,434 ⟶ 3,784:
my_compare(R, K1-_V1, K2-_V2) :-
( K1 < K2 -> R = >; K1 > K2 -> R = <; =).
</syntaxhighlight>
Output :
<pre> ?- ordered_words.
Line 2,457 ⟶ 3,807:
=={{header|PureBasic}}==
<
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()
Line 2,484 ⟶ 3,834:
EndIf
Wend
Else
MessageRequester("Error", "Unable to find dictionary '" + filename + "'")
End
EndIf
SortStructuredList(orderedWords(), #PB_Sort_Ascending, OffsetOf(orderedWord\word), #
SortStructuredList(orderedWords(), #PB_Sort_Descending, OffsetOf(orderedWord\length), #
Define maxLength
FirstElement(orderedWords())
Line 2,496 ⟶ 3,849:
EndIf
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>abbott accent accept access accost almost bellow billow biopsy chilly
Line 2,505 ⟶ 3,858:
=={{header|Python}}==
===Python: First Solution===
<syntaxhighlight lang="python">import urllib.request
url = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
Line 2,512 ⟶ 3,866:
maxlen = len(max(ordered, key=len))
maxorderedwords = [word for word in ordered if len(word) == maxlen]
print(' '.join(maxorderedwords))</
<
mx, url = 0, 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
Line 2,525 ⟶ 3,879:
words, mx = [], lenword
words.append(word)
print(' '.join(words))</
'''Sample Output'''
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</pre>
===Python: As a fold===
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''The longest ordered words in a list'''
from functools import reduce
from operator import le
import urllib.request
# longestOrds :: [String] -> [String]
def longestOrds(ws):
'''The longest ordered words in a given list.
'''
return reduce(triage, ws, (0, []))[1]
# triage :: (Int, [String]) -> String -> (Int, [String])
def triage(nxs, w):
'''The maximum length seen for an ordered word,
and the ordered words of this length seen so far.
'''
n, xs = nxs
lng = len(w)
return (
(lng, ([w] if n != lng else xs + [w])) if (
ordered(w)
) else nxs
) if lng >= n else nxs
# ordered :: String -> Bool
def ordered(w):
'''True if the word w is ordered.'''
return all(map(le, w, w[1:]))
# ------------------------- TEST -------------------------
if __name__ == '__main__':
print(
'\n'.join(longestOrds(
urllib.request.urlopen(
'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'
).read().decode("utf-8").split()
))
)</syntaxhighlight>
{{Out}}
<pre>abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|Quackery}}==
<syntaxhighlight lang="quackery"> [ - -1 1 clamp 1+ ]'[ swap peek do ] is <=> ( n n --> )
[ true swap
behead swap witheach
[ tuck > if
[ dip not conclude ] ]
drop ] is ordered ( [ --> b )
[ stack ] is largest ( [ --> s )
[ 1 largest put
[] swap witheach
[ dup size
largest share <=>
[ drop
[ dup ordered iff
[ nested join ]
else drop ]
[ dup ordered iff
[ dup size largest replace
nip nested ]
else drop ] ] ]
largest release ] is task ( [ --> [ )
$ 'unixdict.txt' sharefile drop nest$
task
witheach [ echo$ sp ]</syntaxhighlight>
{{out}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty </pre>
=={{header|R}}==
<syntaxhighlight lang="r">words = scan("https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt",what = "character")
ordered = logical()
for(i in 1:length(words)){
first = strsplit(words[i],"")[[1]][1:nchar(words[i])-1]
second = strsplit(words[i],"")[[1]][2:nchar(words[i])]
ordered[i] = all(first<=second)
}
cat(words[ordered][which(nchar(words[ordered])==max(nchar(words[ordered])))],sep="\n")</syntaxhighlight>
{{Out}}
<pre>abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(require net/url)
Line 2,557 ⟶ 4,034:
(loop len longs words)
(loop wlen (cons word (if (> wlen len) '() longs)) words)))))
</syntaxhighlight>
Output:
Line 2,577 ⟶ 4,054:
glossy
knotty
</pre>
=={{header|Raku}}==
(formerly Perl 6)
Here we assume the dictionary is provided on standard input.
{{works with|Rakudo|2016.07}}
<syntaxhighlight lang="raku" line>say lines.grep({ [le] .comb }).classify(*.chars).max(*.key).value</syntaxhighlight>
{{out}}
<pre>
[abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty]
</pre>
=={{header|Red}}==
<syntaxhighlight lang="red">Red []
;; code to read url and save to local file:
;;data: read/binary http://www.puzzlers.org/pub/wordlists/unixdict.txt
;;write %unixdict.txt data
max: [ "" ] ;; init array with one empty string (length 0 )
foreach word read/lines %unixdict.txt [ ;; read local file
len: either word = sort copy word [ length? word ] [ -1 ] ;; check if ordered and get length
case [
len > length? first max [ max: reduce [ word ]] ;; init new block
len = length? first max [ append max word ]
]
]
probe max</syntaxhighlight>
'''Sample Output'''
<pre>["abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow" "biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty"]
</pre>
Line 2,589 ⟶ 4,099:
<br>but since the word list (in this case) is already in alphabetical order, this would-be improvement is
<br>mostly moot.
<
iFID
do j=1 while lines(iFID)\==0;
z= _ /*
m= w
@.w= @.w x
end
say
exit /*stick a fork in it, we're all done. */
ghijk
/*──────────────────────────────────────────────────────────────────────────────────────*/
{{out|output|text= when using the default supplied word dictionary:}}
<pre>
16 words found (of length 6)
Line 2,636 ⟶ 4,142:
glossy
knotty
</pre>
=={{header|Ring}}==
<syntaxhighlight lang="ring">
load "stdlib.ring"
cStr = read("unixdict.txt")
wordList = str2list(cStr)
sum = 0
sortList = []
see "working..." + nl + nl
for n = 1 to len(wordList)
num = 0
len = len(wordList[n])-1
for m = 1 to len
asc1 = ascii(wordList[n][m])
asc2 = ascii(wordList[n][m+1])
if asc1 <= asc2
num = num + 1
ok
next
if num = len
sum = sum + 1
add(sortList,[wordList[n],len])
ok
next
sortList = sort(sortList,2)
sortList = reverse(sortList)
endList = []
len = sortList[1][2]
for n = 1 to len(sortList)
if sortList[n][2] = len
add(endList,sortList[n][1])
else
exit
ok
next
endList = sort(endList)
see endList
see nl + "done..." + nl
</syntaxhighlight>
Output:
<pre>
working...
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
done...
</pre>
=={{header|RPL}}==
The only way to use <code>unixdict.txt</code> as input is to download it locally and to convert it into a list of 25104 strings. Fortunately, emulators can handle such a big data structure in RAM.
{{works with|Halcyon Calc|4.2.7}}
≪ "a" DUP
1 4 PICK SIZE '''FOR''' j
SWAP DROP
OVER j DUP SUB
'''IF''' DUP2 > '''THEN''' 99 'j' STO '''END'''
'''NEXT'''
≤ SWAP DROP
≫ '<span style="color:blue">ORDWORD?</span>' STO
≪ 0 → words sizemax
≪ { }
1 words EVAL SIZE '''FOR''' j
words j GET DUP SIZE
'''IF''' DUP sizemax ≥ '''THEN'''
'''IF''' OVER <span style="color:blue">ORDWORD?</span> '''THEN''' <span style="color:grey">@ 2-step test, rather than one with an AND, to save execution time </span>
'''IF''' DUP sizemax > '''THEN'''
'sizemax' STO
SWAP DROP { } SWAP
'''ELSE''' DROP '''END'''
+
'''ELSE''' DROP2 '''END'''
'''ELSE''' DROP2 '''END'''
'''NEXT'''
≫ ≫ '<span style="color:blue">ORDWORDS</span>' STO
'Unixdict' <span style="color:blue">ORDWORDS</span>
{{out}}
<pre>
1: { abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty }
</pre>
=={{header|Ruby}}==
<
ordered_words = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt', 'r').select do |word|
word.strip!
Line 2,646 ⟶ 4,257:
grouped = ordered_words.group_by &:size
puts grouped[grouped.keys.max]</
'''Sample Output'''
Line 2,667 ⟶ 4,278:
knotty</pre>
Local version:
<
puts words.group_by(&:size).sort_by(&:first).last.last</
=={{header|Run BASIC}}==
<
j = 1
i = instr(a$,chr$(10),j)
Line 2,692 ⟶ 4,301:
if len(a3$) = maxL then print a3$
n = n + 1
wend</
<pre>abbott
accent
Line 2,711 ⟶ 4,320:
=={{header|Rust}}==
<syntaxhighlight lang="rust">const FILE: &'static str = include_str!("./unixdict.txt");
fn is_ordered(s: &str) -> bool {
let mut prev = '\x00';
for c in s.to_lowercase().chars() {
if c < prev {
return false;
Line 2,725 ⟶ 4,334:
}
fn find_longest_ordered_words(dict:
let mut result =
let mut longest_length = 0;
for
if is_ordered(&s) {
let n = s.len();
if n > longest_length {
Line 2,737 ⟶ 4,346:
}
if n == longest_length {
result.push(s
}
}
Line 2,746 ⟶ 4,355:
fn main() {
let
let longest_ordered = find_longest_ordered_words(lines);
for s in longest_ordered.iter() {
println!("{}", s.
}
}</
=={{header|Scala}}==
<
/**
Line 2,794 ⟶ 4,384:
val ww = orderedWords( wordsAll ).sortBy( -_.length )
println( ww.takeWhile( _.length == ww.head.length ).mkString("\n") )</
{{out}}
<pre>
Line 2,814 ⟶ 4,404:
knotty
</pre>
=={{header|Scheme}}==
The following implementation uses a <tt>char>=?</tt> procedure that accepts an arbitrary number of arguments. This is allowed, but not required, by R5RS, and is provided by many Scheme implementations. It has been tested under GNU Guile 1.8.8.
<
(define sorted-words
(let ((port (open-input-file "unixdict.txt")))
Line 2,838 ⟶ 4,429:
(newline)))
sorted-words)
</syntaxhighlight>
Output:
Line 2,860 ⟶ 4,451:
=={{header|Seed7}}==
<
const func boolean: isOrdered (in string: word) is func
Line 2,908 ⟶ 4,499:
end if;
write(wordList);
end func;</
Output:
Line 2,931 ⟶ 4,522:
=={{header|Sidef}}==
<
var file = %f'unixdict.txt'
file.open_r(\var fh, \var err) ->
|| die "Can't open file #{file}: $#{err}"
fh.each { |line|
line.trim!
if (line == line.sort)
words[line.length] := []
}
say words[-1].join(' ')
{{out}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</pre>
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
BOOLEAN PROCEDURE ISORDERED(W); TEXT W;
BEGIN
BOOLEAN B;
B := TRUE;
W.SETPOS(1);
IF W.MORE THEN
BEGIN
CHARACTER CURR, LAST;
CURR := W.GETCHAR;
WHILE W.MORE AND B DO
BEGIN
LAST := CURR;
CURR := W.GETCHAR;
B := LAST <= CURR;
END;
END;
ISORDERED := B;
END;
REF (INFILE) INF;
INTEGER LONGEST;
TEXT W;
COMMENT FIND LONGEST LENGTH;
INF :- NEW INFILE("unixdict.txt");
INF.OPEN(BLANKS(132));
WHILE NOT INF.LASTITEM DO
BEGIN
W :- COPY(INF.IMAGE).STRIP;
IF ISORDERED(W) THEN
IF W.LENGTH > LONGEST THEN
LONGEST := W.LENGTH;
INF.INIMAGE;
END;
INF.CLOSE;
COMMENT OUTPUT ORDRERED WORDS OF LONGEST LENGTH;
INF :- NEW INFILE("unixdict.txt");
INF.OPEN(BLANKS(132));
WHILE NOT INF.LASTITEM DO
BEGIN
W :- COPY(INF.IMAGE).STRIP;
IF W.LENGTH = LONGEST AND THEN ISORDERED(W) THEN
BEGIN
OUTTEXT(W);
OUTIMAGE;
END;
INF.INIMAGE;
END;
INF.CLOSE;
END.
</syntaxhighlight>
{{out}}
<pre>
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
14 garbage collection(s) in 0.0 seconds.
</pre>
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
file := FileStream open: 'unixdict.txt' mode: FileStream read.
dict := Set new.
Line 2,967 ⟶ 4,636:
r := (r select: [:w| (w size) = ((r at: 1) size)]) asSortedCollection.
r do: [:e| e displayNl].</
Output:
Line 2,987 ⟶ 4,656:
knotty</pre>
=={{header|SPL}}==
<syntaxhighlight lang="spl">words = #.split(#.readtext("unixdict.txt","ascii"),#.lf)
max = 0
> i, 1..#.size(words,1)
word = words[i]
wordb = #.array(word)
wordbc = #.size(wordb,1)
> j, 3..wordbc,2
<< wordb[j]<wordb[j-2]
<
>> j!>wordbc|wordbc<max
? wordbc>max, result = ""
? wordbc>max, max = wordbc
result += word+#.crlf
<
#.output(result)</syntaxhighlight>
{{out}}
<pre>
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
</pre>
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">fun isOrdered s =
let
fun loop (i, c) =
let
val c' = String.sub (s, i)
in
c <= c' andalso loop (i + 1, c')
end
handle Subscript => true
in
loop (0, #"\^@")
end
fun longestOrdereds (s, prev as (len, lst)) =
let
val len' = size s
in
if len' >= len andalso isOrdered s then
if len' = len then (len, s :: lst) else (len', [s])
else
prev
end
val () = print ((String.concatWith " "
o #2
o foldr longestOrdereds (0, [])
o String.tokens Char.isSpace
o TextIO.inputAll) TextIO.stdIn ^ "\n")</syntaxhighlight>
{{out}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</pre>
=={{header|Swift}}==
<syntaxhighlight lang="swift">import Foundation
guard
let url = NSURL(string: "http://www.puzzlers.org/pub/wordlists/unixdict.txt"),
let input = try? NSString(contentsOfURL: url,encoding: NSUTF8StringEncoding) as String
else { exit(EXIT_FAILURE) }
let words = input.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let group: ([Int: [String]], String) -> [Int: [String]] = {
var d = $0; let g = d[$1.characters.count] ?? []
d[$1.characters.count] = g + [$1]
return d
}
let ordered: ([String], String) -> [String] = {
guard String($1.characters.sort()) == $1 else { return $0 }
return $0 + [$1]
}
let groups = words
.reduce([String](), combine: ordered)
.reduce([Int: [String]](), combine: group)
guard
let maxLength = groups.keys.maxElement(),
let maxLengthGroup = groups[maxLength]
else { exit(EXIT_FAILURE) }
maxLengthGroup.forEach { print($0) }
</syntaxhighlight>
{{Out}}
<pre>
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
</pre>
=={{header|Tcl}}==
<
# Pick the ordered words (of maximal length) from a list
Line 3,013 ⟶ 4,802:
set t [http::geturl "http://www.puzzlers.org/pub/wordlists/unixdict.txt"]
puts [chooseOrderedWords [http::data $t]]
http::cleanup $t</
Output:
<pre>
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
</pre>
=={{header|Transd}}==
<syntaxhighlight lang="Scheme">#lang transd
MainModule: {
_start: (lambda
(with fs FileStream() len 0 maxlen 0 words Vector<String>()
(open-r fs "/mnt/vault/tmp/unixdict.txt") )
(for w in (read-lines fs) do
(= len (size w))
(if (< len maxlen) continue)
(if (is-sorted w)
(if (< maxlen len)
(clear words) (= maxlen len))
(append words w)
))
(lout words)
))
}</syntaxhighlight>
{{out}}
<pre>
["abbott", "accent", "accept", "access", "accost", "almost", "bellow", "billow", "biopsy", "chilly", "choosy", "choppy", "effort", "floppy", "glossy", "knotty"]
</pre>
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
SET data = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
Line 3,048 ⟶ 4,862:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
Output:
<pre>
Line 3,068 ⟶ 4,882:
15. glossy
16. knotty
</pre>
=={{header|Uiua}}==
{{works with|Uiua|0.11.1}}
<syntaxhighlight lang="uiua">
&fras "unixdict.txt" # read file as string
⊜□≠@\n. # split on newlines
▽∵◇(/×≥0°\+utf). # keep ordered words
▽=⊸/↥∵◇⧻. # keep all max length words
</syntaxhighlight>
{{out}}
<pre>
{"abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow" "biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty"}
</pre>
=={{header|Ursala}}==
<
#show+
main = leql@bh$^ eql|= (ordered lleq)*~ unixdict_dot_txt</
* <code>leql</code> is a binary predicate testing a pair of lists for less or equal length
* <code>eql</code> tests for equal length
Line 3,106 ⟶ 4,933:
=={{header|VBA}}==
<syntaxhighlight lang="vba">
Public Sub orderedwords(fname As String)
' find ordered words in dict file that have the longest word length
Line 3,183 ⟶ 5,010:
End If
End Function
</syntaxhighlight>
Results:
Line 3,206 ⟶ 5,033:
knotty
</pre>
=={{header|VBScript}}==
Note: The input file is in the same folder as the script.
<syntaxhighlight lang="vb">Set objFSO = CreateObject("Scripting.FileSystemObject")
Set infile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\" &_
"unixdict.txt",1)
list = ""
length = 0
Do Until inFile.AtEndOfStream
line = infile.ReadLine
If IsOrdered(line) Then
If Len(line) > length Then
length = Len(line)
list = line & vbCrLf
ElseIf Len(line) = length Then
list = list & line & vbCrLf
End If
End If
Loop
WScript.StdOut.Write list
Function IsOrdered(word)
IsOrdered = True
prev_val = 0
For i = 1 To Len(word)
If i = 1 Then
prev_val = Asc(Mid(word,i,1))
ElseIf Asc(Mid(word,i,1)) >= prev_val Then
prev_val = Asc(Mid(word,i,1))
Else
IsOrdered = False
Exit For
End If
Next
End Function</syntaxhighlight>
{{out}}
<pre>abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
=={{header|Vedit macro language}}==
<
#1 = 2 // length of longest word found
Repeat (ALL) {
Line 3,233 ⟶ 5,115:
}
Buf_Quit(OK) // close file
Reg_Type(10) // display results </
<pre>abbott
Line 3,252 ⟶ 5,134:
knotty </pre>
=={{header|
{{trans|Wren}}
<syntaxhighlight lang="Zig">
fn main() {
words := os.read_file("./unixdict.txt") or {println(err) exit(-1)}.split_into_lines()
mut longest_len := 0
mut longest := []string{}
mut u_word := []u8{}
for word in words {
for chars in word {u_word << chars}
u_word.sort()
if word.len > longest_len {
if word == u_word.bytestr() {
longest_len = word.len
longest.clear()
longest << word
}
}
else if word.len == longest_len {
if word == u_word.bytestr() {longest << word}
}
u_word.clear()
}
println("The ${longest.len} ordered words with the longest length (${longest_len}) are:")
print(longest.join("\n"))
}
</syntaxhighlight>
{{out}}
<pre>
The 16 ordered words with the longest length (6) are:
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knott
</pre>
=={{header|Wren}}==
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "io" for File
import "./sort" for Sort
var words = File.read("unixdict.txt").split("\n")
var longestLen = 0
var longest = []
for (word in words) {
if (word.count > longestLen) {
if (Sort.isSorted(word.toList)) {
longestLen = word.count
longest.clear()
longest.add(word)
}
} else if (word.count == longestLen) {
if (Sort.isSorted(word.toList)) longest.add(word)
}
}
System.print("The %(longest.count) ordered words with the longest length (%(longestLen)) are:")
System.print(longest.join("\n"))</syntaxhighlight>
{{out}}
<pre>
The 16 ordered words with the longest length (6) are:
abbott
accent
accept
Line 3,305 ⟶ 5,223:
floppy
glossy
knotty
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">string 0; \use zero-terminated strings
int MaxLen, Pass, I, Ch, Ch0;
char Word(25);
def LF=$0A, CR=$0D, EOF=$1A;
[FSet(FOpen("unixdict.txt", 0), ^I);
MaxLen:= 0;
for Pass:= 1 to 2 do
[OpenI(3);
repeat I:= 0; Ch0:= 0;
loop [repeat Ch:= ChIn(3) until Ch # CR; \remove possible CR
if Ch=LF or Ch=EOF then
[if I > MaxLen then MaxLen:= I;
if I=MaxLen & Pass=2 then
[Word(I):= 0; Text(0, Word); CrLf(0)];
quit;
];
Word(I):= Ch;
if Ch < Ch0 then
[repeat Ch:= ChIn(3) until Ch=LF or Ch=EOF;
quit;
];
Ch0:= Ch;
I:= I+1;
];
until Ch = EOF;
];
]</syntaxhighlight>
{{out}}
<pre>
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
</pre>
=={{header|zkl}}==
One pass, dictionary stays on disk:
<
fcn isLex(word){ word.reduce(fcn(p,c){ (p<=c) and c or T(Void.Stop,False) }) }
File("dict.txt").pump(Void,fcn(w){
Line 3,319 ⟶ 5,287:
})
println("Num words: %d, all size %d\n".fmt(words.len(),sz));
words.pump(Console.println);</
Or, reading dictionary into memory:
<
lwords:=File("dict.txt").readln(*).apply("strip").filter(isLex);
max:=lwords.reduce(fcn(n,w){ w.len()>n and w.len() or n },0);
lwords=lwords.filter(fcn(w,n){ w.len()==n },max);
println("Num words: %d, all size %d\n".fmt(lwords.len(),max));
words.pump(Console.println);</
{{out}}
<pre>
Line 3,347 ⟶ 5,315:
knotty
</pre>
{{omit from|6502 Assembly|unixdict.txt is much larger than the CPU's address space.}}
{{omit from|8080 Assembly|See 6502 Assembly.}}
{{omit from|Z80 Assembly|See 6502 Assembly.}}
|