Skip to content

Instantly share code, notes, and snippets.

@pavloo
Created December 11, 2017 11:45
Show Gist options
  • Save pavloo/16d7ced8a2ea0ccf28ada13188b1e0e0 to your computer and use it in GitHub Desktop.
Save pavloo/16d7ced8a2ea0ccf28ada13188b1e0e0 to your computer and use it in GitHub Desktop.
(defun read-words-from-file (file-path)
(with-temp-buffer
(insert-file-contents file-path)
(mapcar 'split-string (split-string (buffer-string) "\n" t))
)
)
(defun is-all-unique (list predicate)
(let ((n (1- (length list))) (has-similar))
(loop
for i from 0 to (1- n)
do
(loop
for j from (1+ i) to n
do
(when (apply predicate (list (nth i list) (nth j list))) (progn (setq has-similar t) (return)))
;; (print (format "i = %d, j = %d" i j))
)
)
(not has-similar)
)
)
(defun calculate-number-of-unique (list2d predicate)
"Solution for Part #1 and Part #2 http://adventofcode.com/2017/day/4"
(let ((s 0))
(dolist (list list2d)
(when (is-all-unique list predicate) (setq s (1+ s)))
)
s
)
)
(defun build-stat (word)
(let (word-stat letter-kv val)
(dolist (ch (split-string word "" t))
(setq letter-kv (assoc ch word-stat))
(if (not letter-kv) (setq val 1) (setq val (1+ (cdr letter-kv))))
(push `(,ch . ,val) word-stat)
)
word-stat
)
)
(defun is-anagram (word1 word2)
(let (word1-stat word2-stat ch)
(catch 'break
(when (not (= (length word1) (length word2))) (throw 'break nil))
(setq word1-stat (build-stat word1))
(setq word2-stat (build-stat word2))
(dolist (ch (split-string word1 "" t))
(when (not (eq (cdr (assoc ch word1-stat)) (cdr (assoc ch word2-stat)))) (throw 'break nil))
)
t
)
)
)
(is-all-unique '("aa" "bb" "cc" "dd" "ee") 'string=) ;; t
(calculate-number-of-unique (read-words-from-file "./input.txt") 'string=)
(calculate-number-of-unique (read-words-from-file "./input.txt") 'is-anagram)
(is-all-unique '("abcde" "fghij") 'is-anagram) ;; t
(is-all-unique '("abcde" "xyz" "ecdab") 'is-anagram) ;; nil
(is-all-unique '("a" "ab" "abc" "abd" "abf" "abj") 'is-anagram) ;; t
(is-all-unique '("iiii" "oiii" "ooii" "oooi" "oooo") 'is-anagram) ;; t
(is-all-unique '("oiii" "ioii" "iioi" "iiio") 'is-anagram) ;; nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment