Ordered words: Difference between revisions

m
Fix functional CL dict path
(Add COBOL)
imported>GoulashAmateur
m (Fix functional CL dict path)
 
(34 intermediate revisions by 22 users not shown)
Line 24:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V words = File(‘unixdict.txt’).read().split("\n")
V ordered = words.filter(word -> word == sorted(word).join(‘’))
V maxlen = max(ordered, key' w -> w.len).len
V maxorderedwords = ordered.filter(word -> word.len == :maxlen)
print(maxorderedwords.join(‘ ’))</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight Actionlang="action!">CHAR ARRAY line(256)
 
BYTE FUNC IsOrderedWord(CHAR ARRAY word)
Line 93 ⟶ 138:
 
FindWords(fname,max)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Ordered_words.png Screenshot from Atari 8-bit computer]
Line 104 ⟶ 149:
=={{header|Ada}}==
 
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO, Ada.Containers.Indefinite_Vectors;
use Ada.Text_IO;
Line 137 ⟶ 182:
Close (File);
end Ordered_Words;
</syntaxhighlight>
</lang>
 
Output:
Line 158 ⟶ 203:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer
ordered(data s)
{
Line 196 ⟶ 241:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>abbott
Line 217 ⟶ 262:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}.
<syntaxhighlight lang="algol68">PROC ordered = (STRING s)BOOL:
The Algol 68 G "read" PRAGMA is used to include the associative array code from [[Associative_array/Iteration]].
BEGIN
<br>
FOR i TO UPB s - 1 DO IF s[i] > s[i+1] THEN return false FI OD;
Note that as the associative array does not store the elements in sorted order, the output is not sorted.
TRUE EXIT
<lang algol68># find the longrst words in a list that have all letters in order #
return false: FALSE
# use the associative array in the Associate array/iteration task #
END;
PR read "aArray.a68" PR
 
IF FILE input file;
# returns the length of word #
STRING file name = "unixdict.txt";
PROC length = ( STRING word )INT: 1 + ( UPB word - LWB word );
open(input file, file name, stand in channel) /= 0
 
# returns text with the characters sorted into ascending order #
PROC char sort = ( STRING text )STRING:
BEGIN
STRING sorted := text;
FOR end pos FROM UPB sorted - 1 BY -1 TO LWB sorted
WHILE
BOOL swapped := FALSE;
FOR pos FROM LWB sorted TO end pos DO
IF sorted[ pos ] > sorted[ pos + 1 ]
THEN
CHAR t := sorted[ pos ];
sorted[ pos ] := sorted[ pos + 1 ];
sorted[ pos + 1 ] := t;
swapped := TRUE
FI
OD;
swapped
DO SKIP OD;
sorted
END # char sort # ;
 
# read the list of words and store the ordered ones in an associative array #
 
IF FILE input file;
STRING file name = "unixdict.txt";
open( input file, file name, stand in channel ) /= 0
THEN
# failedprint(("Unable to open thefile """ + file #name + """", newline))
print( ( "Unable to open """ + file name + """", newline ) )
ELSE
BOOL at eof := FALSE;
# file opened OK #
on logical file end (input file, (REF FILE f)BOOL: at eof := FALSETRUE);
 
# set the EOF handler for the file #
FLEX [1:0] STRING words;
on logical file end( input file, ( REF FILE f )BOOL:
INT idx := 1;
BEGIN
INT max length := 0;
# note that we reached EOF on the #
 
# latest read #
WHILE NOT at eof
at eof := TRUE;
DO
# return TRUE so processing can continue #
TRUE
END
);
# store the ordered words and find the longest #
INT max length := 0;
REF AARRAY words := INIT LOC AARRAY;
STRING word;
get(input file, (word, newline));
WHILE NOT at eof
IF UPB word >= max length
DO
THEN IF STRING ordered(word;)
THEN
get( input file, ( word, newline ) );
IF char sort( wordmax )length := UPB word;
THEN IF idx > UPB words
# have an ordered word #THEN
IF [1 INT: wordUPB lengthwords :=+ length(20] wordSTRING )tmp;
tmp[1 : UPB wordwords] length:= > max lengthwords;
THEN words := tmp
max length := word lengthFI;
words[idx] FI:= word;
idx #+:= store the word #1
words // word := ""FI
FI
OD;
print(("Maximum length of ordered words: ", whole(max length, -4), newline));
# close the file #
FOR i TO idx-1
close( input file );
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}}==
print( ( "Maximum length of ordered words: ", whole( max length, -4 ), newline ) );
<syntaxhighlight lang="c">
# show the ordered words with the maximum length #
#include <basico.h>
REF AAELEMENT e := FIRST words;
 
WHILE e ISNT nil element DO
#define MAX_LINE 30
IF max length = length( key OF e )
 
THEN
algoritmo
print( ( key OF e, newline ) )
FI;
e :fd= NEXT words0
word={}, result={}
OD
old_word="",new_word=""
FI</lang>
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
Maximum length of ordered words: 6
accent
accept
access
abbott
accost
almost
chilly
bellow
effort
billow
almost
choppy
choosy
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty</pre>
</pre>
 
=={{header|APL}}==
Works in NARS2000 APL; ("Objects" menu -> New, paste this in, save. Then run in the main session manager).
<langsyntaxhighlight APLlang="apl">result←longest_ordered_words file_path
 
f←file_path ⎕NTIE 0 ⍝ open file
Line 338 ⟶ 398:
⍝ find max of word lengths, filter only words with that length
result←ordered_words/⍨lengths=⍨⌈/lengths←≢¨ordered_words
</syntaxhighlight>
</lang>
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.
 
Line 354 ⟶ 414:
=={{header|AppleScript}}==
 
<langsyntaxhighlight 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
Line 396 ⟶ 456:
-- ignoring white space, punctuation and diacriticals
return longestOrderedWords(wordList)
--- end ignoring</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{"abbott", "accent", "accept", "access", "accost", "almost", "bellow", "billow", "biopsy", "chilly", "choosy", "choppy", "effort", "floppy", "glossy", "knotty"}</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">ordered?: function [w]->
w = join sort split w
 
Line 416 ⟶ 476:
maxl: get first ret 'l
print sort map select ret 'x -> maxl = x\l
'x -> x\w</langsyntaxhighlight>
 
{{out}}
Line 426 ⟶ 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">
<lang AutoHotkey>
MaxLen=0
Loop, Read, UnixDict.txt ; Assigns A_LoopReadLine to each line of the file
Line 460 ⟶ 520:
GUIClose:
ExitApp
</syntaxhighlight>
</lang>
Output:
<pre>abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty</pre>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">BEGIN {
abc = "abcdefghijklmnopqrstuvwxyz"
}
Line 500 ⟶ 560:
for (i = 1; i <= best["count"]; i++)
print best[i]
}</langsyntaxhighlight>
 
You must provide <tt>unixdict.txt</tt> as input.
Line 523 ⟶ 583:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="freebasic">'Ordered words - improved version
OPTION COLLAPSE TRUE
 
Line 543 ⟶ 603:
 
PRINT result$
</syntaxhighlight>
</lang>
 
{{out}}
Line 571 ⟶ 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.
<langsyntaxhighlight lang="bbcbasic"> dict% = OPENIN("unixdict.txt")
IF dict%=0 ERROR 100, "Failed to open dictionary file"
Line 589 ⟶ 649:
CLOSE #dict%
PRINT list$
END</langsyntaxhighlight>
'''Output:'''
<pre>
Line 615 ⟶ 675:
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.
 
<langsyntaxhighlight 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#<*#<_</langsyntaxhighlight>
 
{{out}}
Line 637 ⟶ 697:
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}}==
<langsyntaxhighlight lang="bracmat"> ( orderedWords
= bow result longestLength word character
. 0:?bow
Line 662 ⟶ 730:
| !result
)
& orderedWords$"unixdict.txt"</langsyntaxhighlight>
<pre> knotty
glossy
Line 681 ⟶ 749:
 
=={{header|Burlesque}}==
<langsyntaxhighlight lang="burlesque">ln{so}f[^^{L[}>mL[bx(==)[+(L[)+]f[uN</langsyntaxhighlight>
 
{{Out}}
Line 703 ⟶ 771:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <string.h>
#include <stdio.h>
Line 785 ⟶ 853:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
Output:
<pre>abbott
Line 804 ⟶ 872:
knotty</pre>
Alternative version with dynamic array:
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <string.h>
#include <stdio.h>
Line 890 ⟶ 958:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
===Mmap===
Shorter and potentially much faster version with <code>mmap (2)</code>. No stinky <code>malloc</code> or <code>scanf</code> calls.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
Line 946 ⟶ 1,014:
close(fd);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Net;
Line 978 ⟶ 1,046:
return true;
}
}</langsyntaxhighlight>
 
Output:
Line 985 ⟶ 1,053:
=={{header|C++}}==
 
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <fstream>
#include <iostream>
Line 1,022 ⟶ 1,090:
}
std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}</langsyntaxhighlight>
Output:
<pre>
Line 1,045 ⟶ 1,113:
=={{header|Clojure}}==
 
<langsyntaxhighlight Clojurelang="clojure">(defn is-sorted? [coll]
(not-any? pos? (map compare coll (next coll))))
 
Line 1,059 ⟶ 1,127:
take-while-eqcount
(clojure.string/join ", ")
println))</langsyntaxhighlight>
 
Output
<langsyntaxhighlight Clojurelang="clojure">abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">is_ordered = proc (s: string) returns (bool)
last: char := '\000'
for c: char in string$chars(s) do
Line 1,107 ⟶ 1,175:
stream$putl(po, word)
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>accent
Line 1,126 ⟶ 1,194:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. ABC-WORDS.
Line 1,191 ⟶ 1,259:
IF LEN IS EQUAL TO MAXLEN, DISPLAY WORD.
DONE.
EXIT.</langsyntaxhighlight>
{{out}}
<pre>abbott
Line 1,211 ⟶ 1,279:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
ordered_word = (word) ->
for i in [0...word.length - 1]
Line 1,233 ⟶ 1,301:
dict_words = file_content.toString().split '\n'
show_longest_ordered_words dict_words, dict_file_name
</syntaxhighlight>
</lang>
output
<syntaxhighlight lang="text">
> coffee ordered_words.coffee
Longest Ordered Words (source=unixdict.txt):
Line 1,254 ⟶ 1,322:
glossy
knotty
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun orderedp (word)
(reduce (lambda (prev curr)
(when (char> prev curr) (return-from orderedp nil))
Line 1,283 ⟶ 1,351:
("abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow"
"biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty")
</syntaxhighlight>
</lang>
 
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}}==
Line 1,290 ⟶ 1,370:
of the ordered words it finds, and once to actually print the words.
 
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
include "file.coh";
Line 1,372 ⟶ 1,452:
ForEachLine(&fcb, PrintMaxLenWord);
 
var foo := FCBClose(&fcb);</langsyntaxhighlight>
 
{{out}}
Line 1,394 ⟶ 1,474:
=={{header|D}}==
===Simple Procedural Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.string;
 
Line 1,413 ⟶ 1,493:
 
writefln("%-(%s\n%)", result);
}</langsyntaxhighlight>
{{out}}
<pre>abbott
Line 1,434 ⟶ 1,514:
===Faster Procedural Version===
Faster, same output.
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.file, std.range;
 
Line 1,452 ⟶ 1,532:
 
writefln("%-(%s\n%)", result);
}</langsyntaxhighlight>
 
===Functional Version===
Shorter, same output.
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.file, std.string;
 
Line 1,462 ⟶ 1,542:
immutable maxLen = words.map!q{a.length}.reduce!max;
writefln("%-(%s\n%)", words.filter!(w => w.length == maxLen));
}</langsyntaxhighlight>
 
===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}}
<langsyntaxhighlight lang="d">import std.stdio, core.stdc.string, std.mmfile, std.algorithm;
 
const(char)[] findWord(const char[] s) pure nothrow @safe @nogc {
Line 1,507 ⟶ 1,587:
 
txt[0 .. outStart].write;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
program POrderedWords;
 
Line 1,565 ⟶ 1,645:
end;
end.
</syntaxhighlight>
</lang>
 
Output: dictionary directly processed from the URL
 
<syntaxhighlight lang="delphi">
<lang Delphi>
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
</syntaxhighlight>
</lang>
 
=={{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}}
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
 
def words := <http://www.puzzlers.org/pub/wordlists/unixdict.txt>.getText().split("\n")
Line 1,582 ⟶ 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))</langsyntaxhighlight>
 
One-pass procedural algorithm which avoids keeping the entire data set in memory:
 
<langsyntaxhighlight lang="e">def best := [].diverge()
for `@word$\n` ? (word.sort() <=> word) in <http://www.puzzlers.org/pub/wordlists/unixdict.txt> {
if (best.size() == 0) {
Line 1,596 ⟶ 1,731:
}
}
println(" ".rjoin(best.snapshot()))</langsyntaxhighlight>
 
Output: <code>abbott accent accept access accost almost bellow billow biopsy chilly choosy
Line 1,602 ⟶ 1,737:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define (ordered? str)
(for/and ([i (in-range 1 (string-length str))])
Line 1,629 ⟶ 1,764:
;; english
→ (Adelops alloquy beefily begorry billowy egilops)
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight Elixirlang="elixir">File.read!("unixdict.txt")
|> String.split
|> Enum.filter(fn word -> String.codepoints(word) |> Enum.sort |> Enum.join == word end)
Line 1,639 ⟶ 1,774:
|> elem(1)
|> Enum.sort
|> Enum.each(fn word -> IO.puts word end)</langsyntaxhighlight>
 
{{out}}
Line 1,662 ⟶ 1,797:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( ordered_words ).
 
Line 1,684 ⟶ 1,819:
 
words() -> anagrams_deranged:words_from_url( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,694 ⟶ 1,829:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include misc.e
 
type ordered(sequence s)
Line 1,729 ⟶ 1,864:
close(fn)
 
pretty_print(1,words,{2})</langsyntaxhighlight>
 
Output:
Line 1,752 ⟶ 1,887:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
open System.IO
Line 1,764 ⟶ 1,899:
|> Seq.head |> snd
 
longestOrderedWords() |> Seq.iter (printfn "%s")</langsyntaxhighlight>
 
Output:
Line 1,786 ⟶ 1,921:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">
USING: grouping http.client io io.encodings.utf8 io.files
io.files.temp kernel math memoize sequences sequences.extras
Line 1,804 ⟶ 1,939:
word-list [ ordered-word? ] filter
all-longest [ print ] each ;
</syntaxhighlight>
</lang>
 
Output: <pre>( scratchpad ) USING: ordered-words-main ;
Line 1,827 ⟶ 1,962:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,858 ⟶ 1,993:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,866 ⟶ 2,001:
=={{header|FBSL}}==
Downloads the list from puzzlers.org.
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
FUNCTION RESTfulGET(url)
Line 1,899 ⟶ 2,034:
RETURN TRUE
END FUNCTION
</syntaxhighlight>
</lang>
Output
<pre> abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
Line 1,909 ⟶ 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">
<lang Forth>
include lib/stmstack.4th \ include string stack library
 
Line 1,953 ⟶ 2,088:
; \ open file, clear the stack, read file
\ read it back and close the file
ordered</langsyntaxhighlight>
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,976 ⟶ 2,111:
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran">
!***************************************************************************************
module ordered_module
Line 2,090 ⟶ 2,225:
end program main
!****************************************************
</syntaxhighlight>
</lang>
 
'''Output'''
Line 2,096 ⟶ 2,231:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isOrdered(s As Const String) As Boolean
Line 2,137 ⟶ 2,272:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,160 ⟶ 2,295:
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}}==
<langsyntaxhighlight 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
Line 2,191 ⟶ 2,386:
Print sHold.Join(gb.NewLine) 'Display the result
 
End </langsyntaxhighlight>
Output:
<pre>
Line 2,215 ⟶ 2,410:
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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,271 ⟶ 2,466:
fmt.Println(string(bs))
}
}</langsyntaxhighlight>
Output:
<pre>
Line 2,294 ⟶ 2,489:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def isOrdered = { word -> def letters = word as List; letters == ([] + letters).sort() }
assert isOrdered('abbey')
assert !isOrdered('cat')
Line 2,302 ⟶ 2,497:
def owMax = orderedWords*.size().max()
 
orderedWords.findAll { it.size() == owMax }.each { println it }</langsyntaxhighlight>
 
Output:
Line 2,323 ⟶ 2,518:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">
-- Words are read from the standard input. We keep in memory only the current
-- set of longest, ordered words.
Line 2,343 ⟶ 2,538:
let ws = longestOrderedWords $ words str
mapM_ putStrLn ws
</syntaxhighlight>
</lang>
 
Output:
<langsyntaxhighlight lang="haskell">
abbott
accent
Line 2,363 ⟶ 2,558:
glossy
knotty
</syntaxhighlight>
</lang>
Alternative version:
<langsyntaxhighlight lang="haskell">import Control.Monad (liftM)
 
isSorted wws@(_ : ws) = and $ zipWith (<=) wws ws
Line 2,375 ⟶ 2,570:
let ow = filter isSorted ls
let maxl = foldr max 0 (map length ow)
print $ filter (\w -> (length w) == maxl) ow</langsyntaxhighlight>
 
=={{header|Huginn}}==
<langsyntaxhighlight lang="huginn">import Algorithms as algo;
import Mathematics as math;
import Network as net;
Line 2,402 ⟶ 2,597:
print( "{}\n".format( text.join( algo.sorted( maxOrderedWords ), " " ) ) );
return ( 0 );
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Uniconlang="unicon">link strings
 
procedure main(A)
Line 2,414 ⟶ 2,609:
}
every write(!\maxList)
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 2,440 ⟶ 2,635:
 
=={{header|Io}}==
<langsyntaxhighlight Iolang="io">file := File clone openForReading("./unixdict.txt")
words := file readLines
file close
Line 2,456 ⟶ 2,651:
)
 
orderedWords join(" ") println</langsyntaxhighlight>
{{output}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
Line 2,462 ⟶ 2,657:
 
=={{header|J}}==
<syntaxhighlight lang="j">NB. from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt
<lang j> require'web/gethttp'
dictoWords=: gethttp'http://www.puzzlers.org/pub/wordlists(#~ ] = /:~L:0) cutLF fread 'unixdict.txt'
oWords=;:inv (#~ ] (= >./)@:~L:0(#@>)) <;._2 dict-.CRoWords
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</syntaxhighlight>
;:inv (#~ (= >./)@:(#@>))oWords
abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</lang>
 
Recap:
 
# fetchread dictionary (<code>dictfread 'unixdict.txt'</code>)
# break into words, one per line (<code><;._2 dict-.CRcutLF</code>)
# find ordered words (<code>oWords(#~ ] = /:~L:0)</code>)
# select the longest ordered words (<code>(#~ (= >./)@:(#@>))oWords</code>)
# format for display (using ;:inv)
Line 2,479 ⟶ 2,673:
{{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.
<langsyntaxhighlight lang="java5">import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Line 2,521 ⟶ 2,715:
}
}
}</langsyntaxhighlight>
Output:
<pre>abbott
Line 2,539 ⟶ 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]:
 
<langsyntaxhighlight lang="javascript">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;},
Line 2,553 ⟶ 2,780:
};
print(longest.sort().join(', ') + '\n');
});</langsyntaxhighlight>
 
Output:
Line 2,560 ⟶ 2,787:
Alternative version (also using Node.js):
 
<langsyntaxhighlight lang="javascript">var http = require('http');
 
http.get({
Line 2,585 ⟶ 2,812:
console.log(ordered.join(', '));
});
});</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq">def is_sorted:
if length <= 1 then true
else .[0] <= .[1] and (.[1:] | is_sorted)
Line 2,602 ⟶ 2,829:
 
 
split("\n") | longest_ordered_words</langsyntaxhighlight>
{{out}}
["abbott","accent","accept","access","accost","almost","bellow","billow","biopsy","chilly","choosy","choppy","effort","floppy","glossy","knotty"]
Line 2,610 ⟶ 2,837:
 
'''Built-in function''':
<langsyntaxhighlight lang="julia">issorted("abc") # true</langsyntaxhighlight>
 
'''Main''':
<langsyntaxhighlight lang="julia">lst = readlines("data/unixdict.txt")
filter!(issorted, lst)
filter!(x -> length(x) == maximum(length, lst), lst)
println.(lst)</langsyntaxhighlight>
 
{{out}}
Line 2,637 ⟶ 2,864:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> w@&d=|/d:#:'w:d@&&/'{~x<y}':'d:0:"unixdict.txt"
("abbott"
"accent"
Line 2,653 ⟶ 2,880:
"floppy"
"glossy"
"knotty")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
 
<langsyntaxhighlight scalalang="kotlin">import java.ionet.FileURI
 
fun main(args: Array<String>) {
val fileurl = FileURI("unixdict.txt")
"https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"
val result = mutableListOf<String>()
).toURL()
 
val words = url.openStream().bufferedReader().use {
file.forEachLine {
var max = 0
if (it.toCharArray().sorted().joinToString(separator = "") == it) {
result += 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)
 
}
result.sortByDescending { it.length }
</syntaxhighlight>
val max = result[0].length
 
for (word in result) {
if (word.length == max) {
println(word)
}
}
}</lang>
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def maxOrderedWords
 
Line 2,725 ⟶ 2,948:
glossy
knotty
</syntaxhighlight>
</lang>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: >string-index
"" split
"&'0123456789abcdefghijklmnopqrstuvwxyz" "" split
Line 2,764 ⟶ 2,987:
fh fin filtering fh close ;
 
ordered-words</langsyntaxhighlight>
{{out}}
<pre>[ abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty ]</pre>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(f = file('unixdict.txt'), words = array, ordered = array, maxleng = 0)
#f->dowithclose => {
#f->foreachLine => {
Line 2,786 ⟶ 3,009:
with w in #ordered
where #w->size == #maxleng
do => {^ #w + '\r' ^}</langsyntaxhighlight>
{{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">
<lang lb>
'Ordered wordsFrom Rosetta Code
open "unixdict.txt" for input as #1
Line 2,825 ⟶ 3,048:
close #1
print wordList$
</syntaxhighlight>
</lang>
 
Output:
Line 2,847 ⟶ 3,070:
=={{header|Lingo}}==
Code ported from Lua solution.
<langsyntaxhighlight lang="lingo">-- Contents of unixdict.txt passed as string
on printLongestOrderedWords (words)
res = []
Line 2,873 ⟶ 3,096:
end repeat
put res
end</langsyntaxhighlight>
{{Out}}
<pre>-- ["abbott", "accent", "accept", "access", "accost", "almost", "bellow", "billow", "biopsy", "chilly", "choosy", "choppy", "effort", "floppy", "glossy", "knotty"]</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">fp = io.open( "dictionary.txt" )
 
maxlen = 0
Line 2,906 ⟶ 3,129:
end
 
fp:close()</langsyntaxhighlight>
Output:
<pre>abbott
Line 2,926 ⟶ 3,149:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">lst := StringTools:-Split(Import("http://www.puzzlers.org/pub/wordlists/unixdict.txt"), "\n"):
longest := 0:
words := Array():
Line 2,944 ⟶ 3,167:
end if;
end do;
for word in words do print(word); end do;</langsyntaxhighlight>
{{Out|Output}}
<pre>"abbott"
Line 2,964 ⟶ 3,187:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">Module[{max,
data = Select[Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"],
OrderedQ[Characters[#]] &]},
max = Max[StringLength /@ data];
Select[data, StringLength[#] == max &]]
</syntaxhighlight>
</lang>
 
However Mathematica has built in dictionaries for many languages, so here is a more general version...
 
<langsyntaxhighlight Mathematicalang="mathematica">maxWords[language_String] := Module[{max,data = Select[DictionaryLookup[{language, "*"}],OrderedQ[Characters[#]] &]},
max = Max[StringLength /@ data];
Select[data, StringLength[#] == max &]]
</syntaxhighlight>
</lang>
 
<pre>
Line 2,991 ⟶ 3,214:
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight Matlablang="matlab">maxlen = 0;
listlen= 0;
fid = fopen('unixdict.txt','r');
Line 3,006 ⟶ 3,229:
end
fclose(fid);
printf('%s\n',list{:}); </langsyntaxhighlight>
 
Returns:
Line 3,027 ⟶ 3,250:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">import Nanoquery.IO
 
def is_ordered(word)
Line 3,057 ⟶ 3,280:
end
end
println words</langsyntaxhighlight>
 
{{out}}
Line 3,063 ⟶ 3,286:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 3,102 ⟶ 3,325:
Arrays.sort(wchars)
return dword.equalsIgnoreCase(String(wchars))
</syntaxhighlight>
</lang>
;Output
<pre>
Line 3,109 ⟶ 3,332:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
const DictFile = "unixdict.txt"
Line 3,130 ⟶ 3,353:
mx = word.len
words.add word
echo words.join(" ")</langsyntaxhighlight>
{{out}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</pre>
Line 3,136 ⟶ 3,359:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let input_line_opt ic =
try Some(input_line ic)
with End_of_file -> None
Line 3,187 ⟶ 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</langsyntaxhighlight>
 
Output:
Line 3,211 ⟶ 3,434:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: longWords
| w longest l s |
0 ->longest
Line 3,219 ⟶ 3,442:
s longest > ifTrue: [ s ->longest ListBuffer new ->l ]
l add(w)
] l ; </langsyntaxhighlight>
 
{{out}}
Line 3,230 ⟶ 3,453:
{{trans|REXX}}
Adapted for ooRexx
<langsyntaxhighlight lang="oorexx">/*REXX list (the longest) ordered word(s) from a supplied dictionary. */
iFID= 'UNIXDICT.TXT'
w.=''
Line 3,256 ⟶ 3,479:
End
Exit
s: Return left('s',arg(1)>1)</langsyntaxhighlight>
{{out}}
Same as REXX'
 
=={{header|PARI/GP}}==
<langsyntaxhighlight 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)</langsyntaxhighlight>
{{out}}
<pre>%1 = ["abbott", "accent", "accept", "access", "accost", "almost", "bellow", "billow", "biopsy", "chilly", "choosy", "choppy", "effort", "floppy", "glossy", "knotty"]</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use strict;
use warnings;
Line 3,281 ⟶ 3,504:
close FH;
print "@{$words[-1]}\n";
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,288 ⟶ 3,511:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
Copy of [[Ordered_words#Euphoria|Euphoria]]
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang Phix>type ordered(sequence s)
<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>
for i=1 to length(s)-1 do
<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>
-- assume all items in the sequence are atoms
<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>
if s[i]>s[i+1] then
<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>
return 0
<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>
end if
<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>
end for
<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>
return 1
<span style="color: #000000;">found</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end type
<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>
integer maxlen
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
sequence words
<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>
object word
<!--</syntaxhighlight>-->
constant fn = open("demo\\unixdict.txt","r")
maxlen = -1
while 1 do
word = gets(fn)
if atom(word) then
exit
end if
word = trim(word)
if length(word)>=maxlen and ordered(lower(word)) then
if length(word)>maxlen then
maxlen = length(word)
words = {}
end if
words = append(words,word)
end if
end while
close(fn)
?words</lang>
{{out}}
<pre>
The 16 longest ordered words:
{"abbott","accent","accept","access","accost","almost","bellow","billow","biopsy","chilly","choosy","choppy","effort","floppy","glossy","knotty"}
abbott accent accept access
accost almost bellow billow
biopsy chilly choosy choppy
effort floppy glossy knotty
</pre>
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
0 var maxlen
Line 3,355 ⟶ 3,562:
endwhile
f fclose
words print</langsyntaxhighlight>
Another solution
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
0 var f
Line 3,383 ⟶ 3,590:
endwhile
f fclose
print</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight PicoLisplang="picolisp">(in "unixdict.txt"
(mapc prinl
(maxi '((L) (length (car L)))
(by length group
(filter '((S) (apply <= S))
(make (while (line) (link @))) ) ) ) ) )</langsyntaxhighlight>
Output:
<pre>abbott
Line 3,415 ⟶ 3,632:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
order: procedure options (main); /* 24/11/2011 */
declare word character (20) varying;
Line 3,471 ⟶ 3,688:
end in_order;
end order;
</syntaxhighlight>
</lang>
OUTPUT:
<pre>
Line 3,494 ⟶ 3,711:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
$url = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
 
Line 3,511 ⟶ 3,728:
($ordered.Words -join ", ")
Remove-Item -Path "$env:TEMP\unixdict.txt" -Force -ErrorAction SilentlyContinue
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,523 ⟶ 3,740:
Works with SWI-Prolog
 
<langsyntaxhighlight Prologlang="prolog">:- use_module(library( http/http_open )).
 
ordered_words :-
Line 3,567 ⟶ 3,784:
my_compare(R, K1-_V1, K2-_V2) :-
( K1 < K2 -> R = >; K1 > K2 -> R = <; =).
</syntaxhighlight>
</lang>
Output :
<pre> ?- ordered_words.
Line 3,590 ⟶ 3,807:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.s sortLetters(*word.Character, wordLength) ;returns a string with the letters of a word sorted
Protected Dim letters.c(wordLength)
Protected *letAdr = @letters()
Line 3,635 ⟶ 3,852:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>abbott accent accept access accost almost bellow billow biopsy chilly
Line 3,642 ⟶ 3,859:
=={{header|Python}}==
===Python: First Solution===
<langsyntaxhighlight lang="python">import urllib.request
 
url = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
Line 3,649 ⟶ 3,866:
maxlen = len(max(ordered, key=len))
maxorderedwords = [word for word in ordered if len(word) == maxlen]
print(' '.join(maxorderedwords))</langsyntaxhighlight>
 
===Python: Alternate Solution using one explicit loop===
<langsyntaxhighlight lang="python">import urllib.request
 
mx, url = 0, 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
Line 3,662 ⟶ 3,879:
words, mx = [], lenword
words.append(word)
print(' '.join(words))</langsyntaxhighlight>
 
'''Sample Output'''
Line 3,669 ⟶ 3,886:
===Python: As a fold===
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''The longest ordered words in a list'''
 
from functools import reduce
from operator import le
import urllib.request
 
Line 3,691 ⟶ 3,909:
return (
(lng, ([w] if n != lng else xs + [w])) if (
ordWordordered(w)
) else nxs
) if lng >= n else nxs
 
 
# ordWordordered :: String -> Bool
def ordWordordered(w):
'''True if the word w is ordered.'''
return reduceall(stillRisingmap(le, w[1:], (True, w[01:]))[0]
 
 
# ------------------------- TEST -------------------------
# stillRising :: (Bool, Char) -> Char -> (Bool, Char)
def stillRising(bc, x):
'''A boolean value paired with the current character.
The boolean is true if no character in the word
so far has been alphabetically lower than its
predecessor.
'''
b, c = bc
return ((x >= c) if b else b, x)
 
 
# TEST ---
if __name__ == '__main__':
print(
Line 3,721 ⟶ 3,928:
).read().decode("utf-8").split()
))
)</langsyntaxhighlight>
{{Out}}
<pre>abbott
Line 3,742 ⟶ 3,949:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ - -1 1 clamp 1+ ]'[ swap peek do ] is <=> ( n n --> )
 
[ true swap
Line 3,768 ⟶ 3,975:
$ 'unixdict.txt' sharefile drop nest$
task
witheach [ echo$ sp ]</langsyntaxhighlight>
 
{{out}}
Line 3,776 ⟶ 3,983:
=={{header|R}}==
 
<langsyntaxhighlight Rlang="r">words = scan("https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt",what = "character")
 
ordered = logical()
Line 3,785 ⟶ 3,992:
}
 
cat(words[ordered][which(nchar(words[ordered])==max(nchar(words[ordered])))],sep="\n")</langsyntaxhighlight>
{{Out}}
<pre>abbott
Line 3,806 ⟶ 4,013:
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(require net/url)
Line 3,827 ⟶ 4,034:
(loop len longs words)
(loop wlen (cons word (if (> wlen len) '() longs)) words)))))
</syntaxhighlight>
</lang>
 
Output:
Line 3,855 ⟶ 4,062:
 
{{works with|Rakudo|2016.07}}
<syntaxhighlight lang="raku" perl6line>say lines.grep({ [le] .comb }).classify(*.chars).max(*.key).value</langsyntaxhighlight>
 
{{out}}
Line 3,863 ⟶ 4,070:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
;; code to read url and save to local file:
;;data: read/binary http://www.puzzlers.org/pub/wordlists/unixdict.txt
Line 3,877 ⟶ 4,084:
]
]
probe max</langsyntaxhighlight>
'''Sample Output'''
<pre>["abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow" "biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty"]
Line 3,892 ⟶ 4,099:
<br>but since the word list &nbsp; (in this case) &nbsp; is already in alphabetical order, this would-be improvement is
<br>mostly moot.
<langsyntaxhighlight lang="rexx">/*REXX program lists (the longest) ordered word(s) from a supplied dictionary. */
iFID= 'UNIXDICT.TXT' /*the filename of the word dictionary. */
m= 1 /*maximum length of an ordered word(s).*/
Line 3,914 ⟶ 4,121:
ghijk
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return ''; return "s" /*a simple pluralizer (merely adds "S")*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default supplied word dictionary:}}
<pre>
Line 3,938 ⟶ 4,145:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 3,983 ⟶ 4,190:
 
see nl + "done..." + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,006 ⟶ 4,213:
 
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}}==
<langsyntaxhighlight lang="ruby">require 'open-uri'
ordered_words = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt', 'r').select do |word|
word.strip!
Line 4,016 ⟶ 4,257:
 
grouped = ordered_words.group_by &:size
puts grouped[grouped.keys.max]</langsyntaxhighlight>
 
'''Sample Output'''
Line 4,037 ⟶ 4,278:
knotty</pre>
Local version:
<langsyntaxhighlight lang="ruby">words = IO.foreach('unixdict.txt').map(&:chomp).select {|word| word.chars.sort.join == word}
puts words.group_by(&:size).sort_by(&:first).last.last</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">a$ = httpget$("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
j = 1
i = instr(a$,chr$(10),j)
Line 4,060 ⟶ 4,301:
if len(a3$) = maxL then print a3$
n = n + 1
wend</langsyntaxhighlight>
<pre>abbott
accent
Line 4,079 ⟶ 4,320:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">const FILE: &'static str = include_str!("./unixdict.txt");
 
fn is_ordered(s: &str) -> bool {
Line 4,121 ⟶ 4,362:
println!("{}", s.to_string());
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">val wordsAll = scala.io.Source.fromURL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").getLines.toSeq
 
/**
Line 4,143 ⟶ 4,384:
val ww = orderedWords( wordsAll ).sortBy( -_.length )
 
println( ww.takeWhile( _.length == ww.head.length ).mkString("\n") )</langsyntaxhighlight>
{{out}}
<pre>
Line 4,167 ⟶ 4,408:
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.
 
<langsyntaxhighlight lang="scheme">
(define sorted-words
(let ((port (open-input-file "unixdict.txt")))
Line 4,188 ⟶ 4,429:
(newline)))
sorted-words)
</syntaxhighlight>
</lang>
 
Output:
Line 4,210 ⟶ 4,451:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func boolean: isOrdered (in string: word) is func
Line 4,258 ⟶ 4,499:
end if;
write(wordList);
end func;</langsyntaxhighlight>
 
Output:
Line 4,281 ⟶ 4,522:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var words = [[]]
var file = %f'unixdict.txt'
 
Line 4,294 ⟶ 4,535:
}
 
say words[-1].join(' ')</langsyntaxhighlight>
{{out}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</pre>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
 
BOOLEAN PROCEDURE ISORDERED(W); TEXT W;
Line 4,353 ⟶ 4,594:
 
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,379 ⟶ 4,620:
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">|file dict r t|
file := FileStream open: 'unixdict.txt' mode: FileStream read.
dict := Set new.
Line 4,395 ⟶ 4,636:
r := (r select: [:w| (w size) = ((r at: 1) size)]) asSortedCollection.
 
r do: [:e| e displayNl].</langsyntaxhighlight>
 
Output:
Line 4,416 ⟶ 4,657:
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">words = #.split(#.readtext("unixdict.txt","ascii"),#.lf)
max = 0
> i, 1..#.size(words,1)
Line 4,430 ⟶ 4,671:
result += word+#.crlf
<
#.output(result)</langsyntaxhighlight>
{{out}}
<pre>
Line 4,452 ⟶ 4,693:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun isOrdered s =
let
fun loop (i, c) =
Line 4,479 ⟶ 4,720:
o foldr longestOrdereds (0, [])
o String.tokens Char.isSpace
o TextIO.inputAll) TextIO.stdIn ^ "\n")</langsyntaxhighlight>
{{out}}
<pre>abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty</pre>
Line 4,485 ⟶ 4,726:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
guard
Line 4,513 ⟶ 4,754:
 
maxLengthGroup.forEach { print($0) }
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,537 ⟶ 4,778:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require http
 
# Pick the ordered words (of maximal length) from a list
Line 4,561 ⟶ 4,802:
set t [http::geturl "http://www.puzzlers.org/pub/wordlists/unixdict.txt"]
puts [chooseOrderedWords [http::data $t]]
http::cleanup $t</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
SET data = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
Line 4,596 ⟶ 4,862:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,619 ⟶ 4,885:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
 
#show+
 
main = leql@bh$^ eql|= (ordered lleq)*~ unixdict_dot_txt</langsyntaxhighlight>
* <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 4,654 ⟶ 4,920:
 
=={{header|VBA}}==
<syntaxhighlight lang="vba">
<lang VBA>
Public Sub orderedwords(fname As String)
' find ordered words in dict file that have the longest word length
Line 4,731 ⟶ 4,997:
End If
End Function
</syntaxhighlight>
</lang>
 
Results:
Line 4,757 ⟶ 5,023:
=={{header|VBScript}}==
Note: The input file is in the same folder as the script.
<langsyntaxhighlight lang="vb">Set objFSO = CreateObject("Scripting.FileSystemObject")
Set infile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\" &_
"unixdict.txt",1)
Line 4,790 ⟶ 5,056:
End If
Next
End Function</langsyntaxhighlight>
 
{{out}}
Line 4,811 ⟶ 5,077:
 
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang="vedit">File_Open("unixdict.txt", BROWSE)
#1 = 2 // length of longest word found
Repeat (ALL) {
Line 4,836 ⟶ 5,102:
}
Buf_Quit(OK) // close file
Reg_Type(10) // display results </langsyntaxhighlight>
 
<pre>abbott
Line 4,854 ⟶ 5,120:
glossy
knotty </pre>
 
=={{header|V (Vlang)}}==
{{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}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
import "./sort" for Sort
 
var words = File.read("unixdict.txt").split("\n")
Line 4,875 ⟶ 5,190:
}
System.print("The %(longest.count) ordered words with the longest length (%(longestLen)) are:")
System.print(longest.join("\n"))</langsyntaxhighlight>
 
{{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
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
Line 4,900 ⟶ 5,264:
=={{header|zkl}}==
One pass, dictionary stays on disk:
<langsyntaxhighlight lang="zkl">var words=L(), sz=0; // some state
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 4,910 ⟶ 5,274:
})
println("Num words: %d, all size %d\n".fmt(words.len(),sz));
words.pump(Console.println);</langsyntaxhighlight>
Or, reading dictionary into memory:
<langsyntaxhighlight lang="zkl">fcn isLex(word){ word.reduce(fcn(p,c){ (p<=c) and c or T(Void.Stop,False) }) }
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);</langsyntaxhighlight>
{{out}}
<pre>