DEV Community

Discussion on: AoC Day 1: Chronal Calibration

Collapse
 
quoll profile image
Paula Gearon

I made my way here by following @ASpittel. Thanks Ali.

I just finished at Clojure/conj, so it made sense to do today in Clojure. I should consider another language though, since AoC is always a good way to stretch yourself in something new.

Clojure

As per Ryan's suggestions, I pulled the read-file/split operation into it's own lines operation. I also pulled each puzzle into it's own function.

(ns day1
  (:require [clojure.string :refer [split]]))

(defn lines [input-file]
  (split (slurp input-file) #"\n"))

(defn star
  [input-file]
  (->> (lines input-file)
       (map #(Integer/parseInt %))
       (apply +)))

(println (star "input1.txt"))

This highlights something that bugs me about Clojure... there is no built-in function to read a number from a string. It's simple to call out to Java like I just did, but I think there should be something built into the language.

(defn star2
  [input-file]
  (let [numbers (->> (lines input-file) (map #(Integer/parseInt %)))]
    (loop [[n & rn] (cycle numbers) f 0 acc #{}]
      (let [f (+ f n)]
        (if (acc f)
          f
          (recur rn f (conj acc f)))))))

(println (star2 "input1.txt"))

This second puzzle needed something more than a single operation. My first thought was using a reduce function, but then I realized that I needed to keep going through the input over and over until completion, and reduce works on the entire input... unless I created a transducer, which is too much work for something this simple. I probably should have thought about using loop in the first place.