Created
December 12, 2020 08:13
-
-
Save mfcabrera/d7bfa52745603ee0f7be7fd8d34283fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun read-lines (filePath) | |
"Return a list of lines of a file at filePath." | |
(with-temp-buffer | |
(insert-file-contents filePath) | |
(split-string (buffer-string) "\n" t))) | |
(defun parse-spec (s) | |
(let ( (parsed (split-string s " " t) ) ) | |
(list | |
(mapcar 'string-to-number (split-string (car parsed) "-")) | |
(substring (nth 1 parsed) 0 1) | |
(car (last parsed)) | |
) | |
) | |
) | |
(defun count-character-in-str (str char) | |
(let ( (n-times 0) ) | |
(dotimes (i (length str)) | |
(setq n-times (+ n-times | |
(if (string= char ( char-to-string (aref str i))) | |
1 0) | |
)) | |
) | |
n-times | |
)) | |
(defun valid-password? (spec) | |
(let* ( | |
(spec-parsed (parse-spec spec )) | |
(n-chars-pass (count-character-in-str (car (last spec-parsed)) (nth 1 spec-parsed) ) ) | |
(min-char-count (caar spec-parsed)) | |
(max-char-count (car (cdar spec-parsed))) | |
) | |
(if (and (>= n-chars-pass min-char-count ) (<= n-chars-pass max-char-count)) | |
1 0) | |
) | |
) | |
(let ((lines (read-lines "input02.txt"))) | |
(apply '+ (mapcar 'valid-password? lines)) | |
) | |
(defun valid-password-2? (spec) | |
(let* ( | |
(spec-parsed (parse-spec spec)) | |
(password-str (car (last spec-parsed))) | |
(character-to-check (nth 1 spec-parsed) ) | |
(pos1 (caar spec-parsed)) | |
(pos2 (car (cdar spec-parsed))) | |
(num-matching-characters (apply '+ | |
(list | |
(if (string= (char-to-string (aref password-str (- pos1 1))) character-to-check) 1 0) | |
(if (string= (char-to-string (aref password-str (- pos2 1))) character-to-check) 1 0) | |
) | |
)) | |
) | |
(if (eq num-matching-characters 1) 1 0) | |
) | |
) | |
(let ((lines (read-lines "input02.txt"))) | |
(apply '+ (mapcar 'valid-password-2? lines)) | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment