Ordered Words
July 14, 2015
Grep and the system dictionary make word games like this easy:
$ grep "^a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*$" words | grep "......."
aegilops
alloquy
beefily
begorry
belloot
billowy
deglory
egilops
Aegilops is a genus of Eurasian and North American plants in the grass family. Aren’t you glad you know that?
Python.
Added capitals, no requirement there. Otherwise add s.lower() in comparisons.
Scala:
val words = List(“abc”,”cba”, “billowy”, “deglory”, “egilops”, “aZ”, “Za”)
val orderedWords = words.filter(x=>x.toLowerCase==x.toLowerCase.sorted)
val longest= orderedWords.map(x => x.size).max
orderedWords.filter(x=>x.size==longest)
//> res0: List[String] = List(billowy, deglory, egilops)
@Rutger: you forgot to select the longest
Longest:
print sorted([word for word in [‘abc’, ‘cba’, ‘billowy’, ‘deglory’, ‘egilops’, ‘aZ’, ‘Za’] if sorted(word) == list(word)], key=len, reverse=True)[0]
Two more solutions in Python. The first is using a trie. Generatting the trie costs much time, but finding the word is superfast.
According to my sample program, the longest such word in my /usr/share/dict/words file is “Babbitt”.
Some solutions in (Guile) Scheme.
A Haskell version. In order to avoid having to retain all the ordered words in
memory (as would always be the case when sorting by length) I use maxsBy
to keep only the longest ordered words seen so far. Of course, if all the ordered
words have the same length we still lose…
Using as input the dictionary on a Mac:
Solution in R7RS Scheme with SRFI 95.
https://notabug.org/PangolinTurtle/praxis-solutions/raw/master/2015-07-14.scm
scheme@(guile-user)> (ordered-words “/usr/share/dict/words”)
$31 = 7
$32 = (“egilops” “billowy” “begorry” “beefily” “alloquy” “Adelops”)
[…] My racket solution to the Ordered Words Problem on Programming Praxis: […]