new files

This commit is contained in:
Ingy döt Net 2013-04-10 12:38:42 -07:00
parent 3af7344581
commit 86c034bb8b
1364 changed files with 21352 additions and 0 deletions

View file

@ -0,0 +1,3 @@
Define an ordered word as a word in which the letters of the word appear in alphabetic order. Examples include 'abbey' and 'dirt'.
The task is to find ''and display'' all the ordered words in this [http://www.puzzlers.org/pub/wordlists/unixdict.txt dictionary] 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.

View file

@ -0,0 +1,2 @@
---
note: text processing

View file

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

View file

@ -0,0 +1,48 @@
with Ada.Containers.Indefinite_Vectors;
with Ada.Text_IO;
procedure Ordered_Words is
package Word_Vectors is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => String);
function Is_Ordered (The_Word : String) return Boolean is
Highest_Character : Character := 'a';
begin
for I in The_Word'Range loop
if The_Word(I) not in 'a' .. 'z' then
return False;
end if;
if The_Word(I) < Highest_Character then
return False;
end if;
Highest_Character := The_Word(I);
end loop;
return True;
end Is_Ordered;
procedure Print_Word (Position : Word_Vectors.Cursor) is
begin
Ada.Text_IO.Put_Line (Word_Vectors.Element (Position));
end Print_Word;
File : Ada.Text_IO.File_Type;
Ordered_Words : Word_Vectors.Vector;
Max_Length : Positive := 1;
begin
Ada.Text_IO.Open (File, Ada.Text_IO.In_File, "unixdict.txt");
while not Ada.Text_IO.End_Of_File (File) loop
declare
Next_Word : String := Ada.Text_IO.Get_Line (File);
begin
if Is_Ordered (Next_Word) then
if Next_Word'Length > Max_Length then
Max_Length := Next_Word'Length;
Word_Vectors.Clear (Ordered_Words);
Word_Vectors.Append (Ordered_Words, Next_Word);
elsif Next_Word'Length = Max_Length then
Word_Vectors.Append (Ordered_Words, Next_Word);
end if;
end if;
end;
end loop;
Word_Vectors.Iterate (Ordered_Words, Print_Word'Access);
end Ordered_Words;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,8 @@
import urllib.request
url = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
words = urllib.request.urlopen(url).read().decode("utf-8").split()
ordered = [word for word in words if word==''.join(sorted(word))]
maxlen = len(max(ordered, key=len))
maxorderedwords = [word for word in ordered if len(word) == maxlen]
print(' '.join(maxorderedwords))

View file

@ -0,0 +1,11 @@
import urllib.request
mx, url = 0, 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
for word in urllib.request.urlopen(url).read().decode("utf-8").split():
lenword = len(word)
if lenword >= mx and word==''.join(sorted(word)):
if lenword > mx:
words, mx = [], lenword
words.append(word)
print(' '.join(words))

View file

@ -0,0 +1,3 @@
from itertools import groupby
o = (w for w in map(str.strip, open("unixdict.txt")) if sorted(w)==list(w))
print list(next(groupby(sorted(o, key=len, reverse=True), key=len))[1])

View file

@ -0,0 +1,28 @@
/*REXX program lists (longest) ordered words from a supplied dictionary.*/
ifid = 'UNIXDICT.TXT' /*filename of the word dictionary*/
@.= /*placeholder for list of words. */
mL=0 /*maximum length of ordered words*/
call linein ifid,1,0 /*point to the first word in dict*/
/*(above)───in case file is open.*/
do j=1 while lines(ifid)\==0 /*keep reading until exhausted. */
x=linein(ifid); w=length(x) /*get a word and also its length.*/
if w<mL then iterate /*if not long enough, ignore it. */
xU=x; upper xU /*create uppercase version of X.*/
z=left(xU,1) /*now, see if the word is ordered*/
/*handle words of mixed case. */
do k=2 to w; _=substr(xU,k,1) /*process each letter in the word*/
if \datatype(_,'U') then iterate /*Not a letter? Then skip it. */
if _<z then iterate j /*is letter < than the previous ?*/
z=_ /*we have a newer current letter.*/
end /*k*/ /*(above) logic includes ≥ order.*/
mL=w /*maybe define a new maximum len.*/
@.w=@.w x /*add orig. word to a word list.*/
end /*j*/
q=words(@.mL) /*just a handy-dandy var to have.*/
say q 'word's(q) "found (of length" mL')'; say /*show #words & length*/
do n=1 for q; say word(@.mL,n); end /*list all the words. */
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────S subroutine────────────────────────*/
s: if arg(1)==1 then return ''; return 's' /*a simple pluralizer.*/

View file

@ -0,0 +1,8 @@
require 'open-uri'
ordered_words = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt', 'r').select do |word|
word.chomp!
word.split( '' ).sort.join == word
end
grouped = ordered_words.group_by{ |word| word.size }
puts grouped[grouped.keys.max]

View file

@ -0,0 +1,20 @@
(define sorted-words
(let ((port (open-input-file "unixdict.txt")))
(let loop ((char (read-char port)) (word '()) (result '(())))
(cond
((eof-object? char)
(reverse (map (lambda (word) (apply string word)) result)))
((eq? #\newline char)
(loop (read-char port) '()
(let ((best-length (length (car result))) (word-length (length word)))
(cond
((or (< word-length best-length) (not (apply char>=? word))) result)
((> word-length best-length) (list (reverse word)))
(else (cons (reverse word) result))))))
(else (loop (read-char port) (cons char word) result))))))
(map (lambda (x)
(begin
(display x)
(newline)))
sorted-words)

View file

@ -0,0 +1,17 @@
|file dict r t|
file := FileStream open: 'unixdict.txt' mode: FileStream read.
dict := Set new.
"load the whole dict into the set before, 'filter' later"
[ file atEnd ] whileFalse: [
dict add: (file upTo: Character nl) ].
"find those with the sorted letters, and sort them by length"
r := ((dict
select: [ :w | (w asOrderedCollection sort) = (w asOrderedCollection) ] )
asSortedCollection: [:a :b| (a size) > (b size) ] ).
"get those that have length = to the max length, and sort alphabetically"
r := (r select: [:w| (w size) = ((r at: 1) size)]) asSortedCollection.
r do: [:e| e displayNl].

View file

@ -0,0 +1,25 @@
package require http
# Pick the ordered words (of maximal length) from a list
proc chooseOrderedWords list {
set len 0
foreach word $list {
# Condition to determine whether a word is ordered; are its characters
# in sorted order?
if {$word eq [join [lsort [split $word ""]] ""]} {
if {[string length $word] > $len} {
set len [string length $word]
set orderedOfMaxLen {}
}
if {[string length $word] == $len} {
lappend orderedOfMaxLen $word
}
}
}
return $orderedOfMaxLen
}
# Get the dictionary and print the ordered words from it
set t [http::geturl "http://www.puzzlers.org/pub/wordlists/unixdict.txt"]
puts [chooseOrderedWords [http::data $t]]
http::cleanup $t