DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Find Shortest Word In A Given Dictionary (list Of Words)

09.09.2008
| 4312 views |
  • submit to reddit
        // description of your code here


;;Someone asked me: 
;;
;; The attached file contains a sorted list of words, all in lower 
;; case, one word per line, with no spaces. Write a program that reads 
;; such a file and identifies the longest word in the file that can be 
;; constructed by appending shorter words also found in the file. You 
;; may use whichever language you like. Performance matters. 



     (if (< (length (main-args)) 3) 
         (begin 
          (println "Usage: " (main-args 1) " filename") 
               (exit))) 

     (setq file-words (parse (read-file (main-args 2)))) 

     (setq sorted-words (sort file-words (lambda (x y) (> (length x) (length y))))) 

     (setq longest-word-size (length (sorted-words 0))) 

     (define (check-word sub-word-list word) 
         (dolist (sub-word sub-word-list) 
           (replace sub-word word "")) 
       (if (= 0 (length word)) 
             true 
               false)) 

     (dolist (word-x sorted-words) 
       (setq word-save word-x) 
         (setq sub-words " ") 
       (dolist (sub-word file-words) 
           (if (find sub-word word-x) 
                   (if (!= sub-word word-x) 
                           (setq sub-words (append sub-words " " sub-word))))) 
         (setq sub-word-list (parse sub-words)) 
           (setq sub-word-list (sort sub-word-list  (lambda (x y) (> (length x) (length y))))) 
             (while (!= sub-word-list '()) 
             (setq word-x word-save) 
                 (if (check-word sub-word-list word-x) 
                     (begin 
                          (println "found: " word-save) 
                               (exit))) 
                 (setq sub-word-list (rest sub-word-list))))