Optimal Alphabetical Order
May 14, 2013
Brian Kell, who wrote the page we are looking at, gives a list of 67,230 words that we read into a list of lists of characters in the variable words:
(define (get-words filename)
(with-input-from-file filename
(lambda ()
(let loop ((word (read-line)) (words (list)))
(if (eof-object? word) (reverse words)
(let ((word (map char-upcase (string->list word))))
(loop (read-line) (cons word words))))))))
(define words (get-words "words.txt"))
The key defines the alphabetical ordering of the letters in a word. Here we define the base key, which is the standard alphabet, and write a function that displays a key; the key is stored as a vector of positions, indexed by the alphabet with A = 1 and Z = 26:
(define alpha (vector 1 2 3 4 5 6 7 8 9 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24 25 26))
(define (display-key key)
(let loop ((ks (vector->list key)) (xs (list)))
(if (null? ks)
(list->string (reverse xs))
(loop (cdr ks) (cons (integer->char (+ (car ks) 64)) xs)))))
Function alpha?
determines if a word is in alphabetical order according to the current key:
(define (alpha? word key)
(let loop ((cs word) (prev 0))
(if (null? cs) #t
(let ((curr (vector-ref key (- (char->integer (car cs)) 65))))
(if (< curr prev) #f (loop (cdr cs) curr))))))
Then we can count the number of words in the word list that are in alphabetical order according to the given key:
(define (count words key)
(length (filter (lambda (w) (alpha? w key)) words)))
To find the key that produces the maximum number of words in alphabetical order, we will use a kind of hill-climbing technique. Each time through the main loop
we compute the number of words that are in alphabetical order according to the current key. If the new key improves on the current key, we display the new key and keep the new maximum in prev. Then we compute a new key and loop. Most of the time the new key is computed by swapping two letters in the current key, using a function alter
. Every 2000 times through the loop we call alter
an extra time, and every 50000 times through the loop we call alter
three extra times; the idea is to move more quickly to another local maximum. Every million times through the loop we shuffle the key, potentially moving every letter in the key, so that we can restart the search for a new local maximum:
(define (climb words key)
(let ((prev (count words key)))
(display (display-key key))
(display " ") (display prev) (newline)
(let loop ((key key) (prev prev))
(let* ((new-key (alter key))
(score (count words new-key)))
(cond ((< prev score)
(display (display-key key))
(display " ") (display score) (newline)
(loop new-key score))
((zero? (randint 1000000))
(loop (shuffle key) prev))
((zero? (randint 50000))
(loop (alter (alter (alter new-key))) prev))
((zero? (randint 2000))
(loop (alter new-key) prev))
(else (loop key prev)))))))
Here are the alter
and shuffle
functions.
(define (alter key)
(let ((p (randint 0 26)) (q (randint 0 26)))
(let ((t (vector-ref key p)))
(vector-set! key p (vector-ref key q))
(vector-set! key q t)))
key)
(define (shuffle vec)
(do ((n (vector-length vec) (- n 1)))
((zero? n) vec)
(let* ((r (randint n)) (t (vector-ref vec r)))
(vector-set! vec r (vector-ref vec (- n 1)))
(vector-set! vec (- n 1) t))))
To run the program, say (climb words (shuffle alpha))
The best key I found at the time of writing is KADVQXLHNJCRIOGTBEYPMUFSZW, which gives 2328 words in alphabetical order, but I left the program running on my machine at work and hope to have a better key in the morning; on his web page, Kell gives a key with 4046 words in alphabetical order.
We used randint from the Standard Prelude. You can run the program at http://programmingpraxis.codepad.org/DLzOQf2A, which provides a small dictionary for demonstration and testing. The best key I found for that small dictionary is ELBVYMOCJDRGXKHAWUNTPFIQZS, which gives 16 words in alphabetical order.
This Python version gives a score of 4038 words in right order after about 3.5 minutes.
Sorry for not solving the actual quiz, but reading this problem I’ve become curious, what would be the result if we interpret the word list as an ordered character preference vote, and run a Concorcet (in this case Schulze) method on them. http://en.wikipedia.org/wiki/Schulze_method
If my Haskell program is correct (I haven’t tested it… :() the result is:
“EAIORSLNTUCDGPMHBYKFWVZJXQ”
(in this particular case I’ve simply removed duplicate characters from all word, maybe other ways of handling duplicates is possible to)
Cleared up the code a bit (using pairs instead of lists, correcting typos, etc…) here: http://hpaste.org/87967
Still offtopic :$ but intresetnig this Schulze voting was much ado about nothing, the result:
EAIORSLNTUCDGPMHBYKFWVZJXQ
is nearly the identical to the one we get from character frequencies
ESAIORLNTUDCGPMHBYFKWVZJXQ
If we don’t follow the requirement about handling the missing characters (they get quite much down-vote when they are not there) the result is:
JQVFWZBPHUMKCOALTIRNESGDYX
This should represent the usual character order in words better – I guess.
The process can be speeded up enormously using a Trie to store all the words. Then counting the words in the right order is about a factor 10 faster. I will post code later. I get now 4046 words in correct order with key=CWBFJHLOAQUMPVXINTKGZERDYS after 134 seconds. I do not get this answer with every run, as it it a random optimization.
Interesting. I actually worked out this problem about four months ago for one of the Hard challenges on the /r/DailyProgrammer subreddit: [01/25/13] Challenge #118 [Hard] Alphabetizing cipher (albeit with a smaller dictionary).
Given the appropriate helper functions (see blog post below), here’s my basic Racket solution (it uses hill climbing and randomization on finding a local maximum):
Blog post (with the above solution and a few more zany matrix based things that never ended up going anywhere): An optimal alphabetizing cipher
Full source (on GitHub): alphabetizing-cipher.rkt on GitHub
(While writing this post, I’ve found a few solutions just under 4000. I’ll let it run overnight and see what happens.)
By the way I think that this problem is equivalent with the NP-hard maximum clique problem: if we make the graph by connecting two words if there exist an alphabet such that both words have all their letters in alphabetical order, then from the cliques (where each word is connected with each other) would be easy to generate an appropriate alphabet
my pythons: http://pastebin.com/XgxQmF7W
best = “JQBPCOUFVWMHAXZTRLIKNGEDSY” # 3038 words
@szemet: Yes, a maximal clique would give an optimal answer. But the runtime is so ridiculously bad… If you check my link(s) above, I implemented the Bron-Kerbosch algorithm to try and solve it that way, but after about two months the largest clique it had found was only 46 words (on the smaller dictionary). This is definitely one of the classes of problems where a statistical approach will be better. It may be possible to speed up the problem a bit more with some domain specific knowledge, but I’m not sure how.
Here is the Python code using a trie to represent te words. The fastest solution sofar was 26 seconds with a score of 4046 and key BPCHFLJOWAQUXMVINKGTZERDYS.