Skip to main content
1 of 2
Phrancis
  • 20.4k
  • 6
  • 68
  • 154

Advent of Code: "Not Quite Lisp"

I have solved this simple challenge on Advent of Code:

Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.

An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor.

The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors.

This is my first time trying out Lisp (and functional programming at all) and would like to see if there is anything that I could do better, or more "functionally".

I wrote the function in a manner to be quite generic, i.e., it can take any input string, and any two characters. It returns a list containing the amount of up and down characters along with the difference between the two (which is the answer to the challenge). Demo on Coding Ground

(defun count-up-down-characters-with-difference (input-string up-char down-char)
    "Given a string of any length, iterate each character of the string looking for up- and down-characters
        provided by the caller, and return the number of each, as well as the difference between them."
    (setf count-up 0) 
    (setf count-down 0)
    (loop for c across input-string do
        (if (char-equal c up-char) 
            (incf count-up))
        (if (char-equal c down-char) 
            (decf count-down)))
    (list count-up count-down (+ count-up count-down)))

Example generic usage:

(setf night-before-xmas "'Twas the night before Christmas, when all through the house, Not a creature was stirring, not even a mouse; The stockings were hung by the chimney with care, In hopes that St. Nicholas soon would be there;")
(time (print (count-up-down-characters-with-difference night-before-xmas #\e #\a)))    
;; prints:
;(21 -10 11)                                                                                                                                                     
;Real time: 5.97E-4 sec.                                                                                                                                         
;Run time: 5.7E-4 sec.                                                                                                                                           
;Space: 1400 Bytes     
Phrancis
  • 20.4k
  • 6
  • 68
  • 154