exercism

Exercism solutions.
git clone git://code.dwrz.net/exercism
Log | Files | Refs

anagram.el (1586B)


      1 ;;; anagram.el --- Anagram (exercism)
      2 
      3 ;;; Commentary:
      4 
      5 ;;; Code:
      6 
      7 (provide 'anagram)
      8 
      9 (defun get-char-count (w)
     10   "Return an associative list of character counts for W."
     11   (let ((char-list (string-to-list w))
     12         (char-count ()))
     13     ;; Build an associative list from the character list.
     14     (dolist (char char-list char-count)
     15       (let ((entry (assoc char char-count)))
     16         (if entry (cl-incf (cdr entry))
     17           (push (cons char 1) char-count))))))
     18 
     19 (defun equal-char-count (char-count comparison-char-count)
     20   "Return t if the submitted character counts are equal, false otherwise.
     21 CHAR-COUNT and COMPARISON-CHAR-COUNT should be alists in (character . count) format."
     22   (let ((are-equal t))
     23     (dolist (char-count char-count are-equal)
     24       (if (not are-equal) nil)
     25       (if (assoc (car char-count) comparison-char-count)
     26           (if (not (equal
     27                     (cdr char-count)
     28                     (cdr (assoc (car char-count) comparison-char-count))))
     29               (setq are-equal nil))
     30         (setq are-equal nil)))))
     31 
     32 (defun anagrams-for (word anagrams)
     33   "Return all elements of ANAGRAMS which are anagrams for WORD.
     34 Case insensitive."
     35   (let ((candidates ())
     36         (word-char-count (get-char-count (downcase word))))
     37     (dolist (candidate anagrams candidates)
     38       (when (and (not (string-equal word candidate))
     39                  (= (length word) (length candidate))
     40                  (equal-char-count word-char-count (get-char-count (downcase candidate))))
     41         (push candidate candidates)))
     42     (reverse candidates)))
     43 
     44 ;;; anagram.el ends here