August 12, 2018

Advent of Code 2015 Day 1 - Not Quite Lisp

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.

For example:

  • (()) and ()() both result in floor 0.
  • ((( and (()(()( both result in floor 3.
  • ))((((( also results in floor 3.
  • ()) and ))( both result in floor -1 (the first basement level).
  • ))) and )())()) both result in floor -3.

To what floor do the instructions take Santa?

(ns day01
  (:require [cljs.test :refer-macros [deftest is run-tests]]))

(defn part-1 [s]
  (- (count (re-seq #"\(" s))
     (count (re-seq #"\)" s))))

(deftest test-part-1
  (is (= 0 (part-1 "(())") (part-1 "()()")))
  (is (= 3 (part-1 "(((") (part-1 "(()(()(") (part-1 "))(((((")))
  (is (= -1 (part-1 "())") (part-1 "))(")))
  (is (= -3 (part-1 ")))") (part-1 ")())())"))))
  
(run-tests)

Part 2

Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on.

For example:

  • ) causes him to enter the basement at character position 1.
  • ()()) causes him to enter the basement at character position 5.

What is the position of the character that causes Santa to first enter the basement?

(defn parse-step [floor step]
  (case step
    \( (inc floor)
    \) (dec floor)
    floor))

(defn part-2 [s]
  (dec (->> s
            (reductions parse-step 0)
            (map vector (drop 1 (range)))
            (drop-while (fn [[position floor]] (not (neg? floor))))
            first
            first)))

(deftest test-part-2
  (is (= 1 (part-2 ")"))
  (is (= 5 (part-2 "()())")))))

(run-tests)
Tags: coding exercises KLIPSE Clojure Advent of Code