Skip to content

Instantly share code, notes, and snippets.

@mfcabrera
Created December 12, 2020 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfcabrera/d7bfa52745603ee0f7be7fd8d34283fe to your computer and use it in GitHub Desktop.
Save mfcabrera/d7bfa52745603ee0f7be7fd8d34283fe to your computer and use it in GitHub Desktop.
(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